BaseDynamicGrid.cs 51 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730
  1. using InABox.Core;
  2. using InABox.Wpf;
  3. using InABox.WPF;
  4. using Syncfusion.Data;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.ComponentModel;
  8. using System.Diagnostics;
  9. using System.Diagnostics.CodeAnalysis;
  10. using System.Linq;
  11. using System.Linq.Expressions;
  12. using System.Text;
  13. using System.Threading;
  14. using System.Threading.Tasks;
  15. using System.Windows;
  16. using System.Windows.Controls;
  17. using System.Windows.Input;
  18. using System.Windows.Media;
  19. using System.Windows.Media.Animation;
  20. using System.Windows.Media.Imaging;
  21. using Color = System.Drawing.Color;
  22. namespace InABox.DynamicGrid;
  23. public abstract class BaseDynamicGrid : ContentControl, IDynamicGridUIComponentParent
  24. {
  25. public static readonly DependencyProperty UseWaitCursorProperty =
  26. DependencyProperty.Register(nameof(UseWaitCursor), typeof(bool), typeof(BaseDynamicGrid));
  27. public bool UseWaitCursor
  28. {
  29. get => (bool)GetValue(UseWaitCursorProperty);
  30. set => SetValue(UseWaitCursorProperty, value);
  31. }
  32. public static readonly DependencyProperty ItemsSourceProperty =
  33. DependencyProperty.Register(
  34. nameof(ItemsSource),
  35. typeof(object),
  36. typeof(BaseDynamicGrid),
  37. new PropertyMetadata(null, DoItemsSourceChanged)
  38. );
  39. private static void DoItemsSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  40. {
  41. if (d is BaseDynamicGrid dynamicGrid)
  42. {
  43. dynamicGrid.OnItemSourceChanged(e.NewValue);
  44. }
  45. }
  46. public object? ItemsSource
  47. {
  48. get => GetValue(ItemsSourceProperty);
  49. set => SetValue(ItemsSourceProperty, value);
  50. }
  51. public abstract void OnItemSourceChanged(object value);
  52. protected enum ClipAction
  53. {
  54. Cut,
  55. Copy
  56. }
  57. private IDynamicGridUIComponent UIComponent;
  58. private UIElement? _header;
  59. private readonly Button Add;
  60. public bool bRefreshing;
  61. bool IDynamicGridUIComponentParent.IsRefreshing => bRefreshing;
  62. private readonly Label ClipboardSpacer;
  63. private readonly Button Copy;
  64. private readonly Label Count;
  65. private readonly Border Disabler;
  66. private readonly DynamicActionColumn? drag;
  67. private readonly Button Delete;
  68. private readonly DockPanel Docker;
  69. private readonly Button Edit;
  70. private readonly Label EditSpacer;
  71. private readonly Button? ExportButton;
  72. private readonly Label ExportSpacer;
  73. private readonly Button? DuplicateBtn;
  74. private readonly Button SwitchViewBtn;
  75. private readonly Button? Help;
  76. private readonly Button? ImportButton;
  77. private readonly Grid Layout;
  78. private readonly Label Loading;
  79. private readonly DoubleAnimation LoadingFader = new(1d, 0.2d, new Duration(TimeSpan.FromSeconds(2))) { AutoReverse = true };
  80. private readonly Button Print;
  81. private readonly Label PrintSpacer;
  82. private readonly StackPanel LeftButtonStack;
  83. private readonly StackPanel RightButtonStack;
  84. protected DynamicGridRowStyleSelector RowStyleSelector;
  85. protected virtual bool CanDuplicate { get; } = false;
  86. #region Events
  87. private event IDynamicGrid.ReconfigureEvent? _onReconfigure;
  88. public event IDynamicGrid.ReconfigureEvent? OnReconfigure
  89. {
  90. add
  91. {
  92. _onReconfigure += value;
  93. Reconfigure();
  94. }
  95. remove
  96. {
  97. _onReconfigure -= value;
  98. Reconfigure();
  99. }
  100. }
  101. public OnGetDynamicGridRowStyle? OnGetRowStyle { get; set; }
  102. public event OnPrintData? OnPrintData;
  103. public event BeforeRefreshEventHandler? BeforeRefresh;
  104. public event AfterRefreshEventHandler? AfterRefresh;
  105. /// <summary>
  106. /// Called when an item is selected in the grid. It is not called if <see cref="IsReady"/> is not <see langword="true"/>.
  107. /// </summary>
  108. /// <remarks>
  109. /// It is unnecessary to use this if within a grid. Instead, override <see cref="SelectItems(CoreRow[]?)"/>.
  110. /// </remarks>
  111. public event SelectItemHandler? OnSelectItem;
  112. public event OnCellDoubleClick? OnCellDoubleClick;
  113. public event EventHandler? OnChanged;
  114. public delegate void BeforeSelectionEvent(CancelEventArgs cancel);
  115. public event BeforeSelectionEvent? OnBeforeSelection;
  116. protected virtual void Changed()
  117. {
  118. }
  119. public virtual void DoChanged()
  120. {
  121. Changed();
  122. OnChanged?.Invoke(this, EventArgs.Empty);
  123. }
  124. public event OnFilterRecord? OnFilterRecord;
  125. public event OnDoubleClick? OnDoubleClick;
  126. #endregion
  127. protected DynamicGridSettings Settings { get; set; }
  128. public BaseDynamicGrid() : base()
  129. {
  130. UseWaitCursor = true;
  131. Options = new DynamicGridOptions();
  132. Options.OnChanged += () =>
  133. {
  134. _hasLoadedOptions = true;
  135. OptionsChanged();
  136. };
  137. ActionColumns = new DynamicActionColumns();
  138. ColumnGroupings = new DynamicGridColumnGroupings();
  139. RowStyleSelector = GetRowStyleSelector();
  140. RowStyleSelector.GetStyle += (row, style) => GetRowStyle(row, style);
  141. IsReady = false;
  142. Data = new CoreTable();
  143. drag = new DynamicImageColumn(InABox.Wpf.Resources.drag.AsBitmapImage()) { Position = DynamicActionColumnPosition.Start };
  144. VisibleColumns = new DynamicGridColumns();
  145. PreInit();
  146. UIComponent = CreateUIComponent();
  147. Loading = new Label();
  148. Loading.Content = "Loading...";
  149. Loading.Foreground = new SolidColorBrush(Colors.White);
  150. Loading.VerticalContentAlignment = VerticalAlignment.Center;
  151. Loading.HorizontalContentAlignment = HorizontalAlignment.Center;
  152. Loading.Visibility = Visibility.Collapsed;
  153. Loading.SetValue(Panel.ZIndexProperty, 999);
  154. Loading.SetValue(Grid.RowProperty, 1);
  155. Loading.FontSize = 14.0F;
  156. LoadingFader.Completed += (sender, args) =>
  157. {
  158. if (Loading.Visibility == Visibility.Visible)
  159. {
  160. //Logger.Send(LogType.Information, this.GetType().EntityName().Split(".").Last(), "Loading Fader Restarting");
  161. Loading.BeginAnimation(Label.OpacityProperty, LoadingFader);
  162. }
  163. };
  164. if(this is IHelpDynamicGrid helpGrid)
  165. {
  166. Help = CreateButton(Wpf.Resources.help.AsBitmapImage(Color.White));
  167. Help.Margin = new Thickness(0, 2, 2, 0);
  168. Help.SetValue(DockPanel.DockProperty, Dock.Right);
  169. Help.Click += (o, e) => ShowHelp(helpGrid.HelpSlug());
  170. }
  171. Add = CreateButton(Wpf.Resources.add.AsBitmapImage(Color.White));
  172. Add.Margin = new Thickness(0, 2, 2, 0);
  173. Add.Click += Add_Click;
  174. Edit = CreateButton(Wpf.Resources.pencil.AsBitmapImage(Color.White));
  175. Edit.Margin = new Thickness(0, 2, 2, 0);
  176. Edit.Click += Edit_Click;
  177. SwitchViewBtn = CreateButton(Wpf.Resources.alter.AsBitmapImage());
  178. SwitchViewBtn.Margin = new Thickness(0, 2, 2, 0);
  179. SwitchViewBtn.Click += SwitchView_Click;
  180. EditSpacer = new Label { Width = 5 };
  181. Print = CreateButton(Wpf.Resources.print.AsBitmapImage(Color.White));
  182. Print.Margin = new Thickness(0, 2, 2, 0);
  183. Print.Click += (o, e) => DoPrint(o);
  184. PrintSpacer = new Label { Width = 5 };
  185. Copy = CreateButton(Wpf.Resources.duplicate.AsBitmapImage(Color.White), tooltip: "Duplicate Rows");
  186. Copy.Margin = new Thickness(0, 2, 2, 0);
  187. Copy.Click += Copy_Click;
  188. ClipboardSpacer = new Label { Width = 5 };
  189. if(this is IExportDynamicGrid)
  190. {
  191. ExportButton = CreateButton(Wpf.Resources.doc_xls.AsBitmapImage(Color.White), "Export");
  192. ExportButton.Margin = new Thickness(0, 2, 2, 0);
  193. ExportButton.Click += ExportButtonClick;
  194. }
  195. if(this is IImportDynamicGrid)
  196. {
  197. ImportButton = CreateButton(Wpf.Resources.doc_xls.AsBitmapImage(Color.White), "Import");
  198. ImportButton.Margin = new Thickness(0, 2, 2, 0);
  199. ImportButton.Click += ImportButton_Click;
  200. }
  201. ExportSpacer = new Label { Width = 5 };
  202. LeftButtonStack = new StackPanel();
  203. LeftButtonStack.Orientation = Orientation.Horizontal;
  204. LeftButtonStack.SetValue(DockPanel.DockProperty, Dock.Left);
  205. if(Help is not null)
  206. {
  207. LeftButtonStack.Children.Add(Help);
  208. }
  209. LeftButtonStack.Children.Add(Add);
  210. LeftButtonStack.Children.Add(Edit);
  211. LeftButtonStack.Children.Add(SwitchViewBtn);
  212. //Stack.Children.Add(MultiEdit);
  213. LeftButtonStack.Children.Add(EditSpacer);
  214. LeftButtonStack.Children.Add(Print);
  215. LeftButtonStack.Children.Add(PrintSpacer);
  216. LeftButtonStack.Children.Add(Copy);
  217. LeftButtonStack.Children.Add(ClipboardSpacer);
  218. if(ExportButton is not null)
  219. {
  220. LeftButtonStack.Children.Add(ExportButton);
  221. }
  222. if(ImportButton is not null)
  223. {
  224. LeftButtonStack.Children.Add(ImportButton);
  225. }
  226. if(ExportButton is not null || ImportButton is not null)
  227. {
  228. LeftButtonStack.Children.Add(ExportSpacer);
  229. }
  230. RightButtonStack = new StackPanel();
  231. RightButtonStack.Orientation = Orientation.Horizontal;
  232. RightButtonStack.SetValue(DockPanel.DockProperty, Dock.Right);
  233. Delete = CreateButton(Wpf.Resources.delete.AsBitmapImage(Color.White));
  234. Delete.Margin = new Thickness(2, 2, 0, 0);
  235. Delete.SetValue(DockPanel.DockProperty, Dock.Right);
  236. Delete.Click += Delete_Click;
  237. if(this is IDuplicateDynamicGrid)
  238. {
  239. DuplicateBtn = AddButton("Duplicate", Wpf.Resources.paste.AsBitmapImage(Color.White), DuplicateButton_Click);
  240. }
  241. Count = new Label();
  242. Count.Height = 30;
  243. Count.Margin = new Thickness(0, 2, 0, 0);
  244. Count.VerticalContentAlignment = VerticalAlignment.Center;
  245. Count.HorizontalContentAlignment = HorizontalAlignment.Center;
  246. Count.SetValue(DockPanel.DockProperty, Dock.Left);
  247. Docker = new DockPanel();
  248. Docker.SetValue(Grid.RowProperty, 2);
  249. Docker.SetValue(Grid.ColumnProperty, 0);
  250. Docker.Children.Add(LeftButtonStack);
  251. Docker.Children.Add(Delete);
  252. Docker.Children.Add(RightButtonStack);
  253. Docker.Children.Add(Count);
  254. Layout = new Grid();
  255. Layout.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
  256. Layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  257. Layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
  258. Layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  259. var control = UIComponent.Control;
  260. control.SetValue(Grid.RowProperty, 1);
  261. Layout.Children.Add(control);
  262. Layout.Children.Add(Loading);
  263. Layout.Children.Add(Docker);
  264. Disabler = new Border()
  265. {
  266. BorderBrush = new SolidColorBrush(Colors.Transparent),
  267. Background = new SolidColorBrush(Colors.DimGray) { Opacity = 0.2 },
  268. Visibility = Visibility.Collapsed,
  269. };
  270. Disabler.SetValue(Canvas.ZIndexProperty, 99);
  271. Disabler.SetValue(Grid.RowSpanProperty, 3);
  272. Layout.Children.Add(Disabler);
  273. //Scroll.ApplyTemplate();
  274. Content = Layout;
  275. IsEnabledChanged += (sender, args) =>
  276. {
  277. Disabler.Visibility = Equals(args.NewValue, true)
  278. ? Visibility.Collapsed
  279. : Visibility.Visible;
  280. };
  281. Settings = LoadSettings();
  282. Init();
  283. Reconfigure();
  284. }
  285. protected virtual void PreInit()
  286. {
  287. }
  288. #region IDynamicGridUIComponentParent
  289. protected virtual IDynamicGridUIComponent CreateUIComponent()
  290. {
  291. return new DynamicGridGridUIComponent()
  292. {
  293. Parent = this
  294. };
  295. }
  296. protected IDynamicGridUIComponent GetUIComponent() => UIComponent;
  297. bool IDynamicGridUIComponentParent.CanFilter()
  298. {
  299. return !Options.ReorderRows || !Options.EditRows;
  300. }
  301. bool IDynamicGridUIComponentParent.CanSort()
  302. {
  303. return !Options.ReorderRows || !Options.EditRows;
  304. }
  305. DynamicGridRowStyleSelector IDynamicGridUIComponentParent.RowStyleSelector => RowStyleSelector;
  306. void IDynamicGridUIComponentParent.BeforeSelection(CancelEventArgs cancel)
  307. {
  308. BeforeSelection(cancel);
  309. }
  310. void IDynamicGridUIComponentParent.SelectItems(CoreRow[] rows)
  311. {
  312. SelectItems(rows);
  313. }
  314. void IDynamicGridUIComponentParent.HandleKey(KeyEventArgs e)
  315. {
  316. if (Options.ReorderRows)
  317. {
  318. if (e.Key == Key.X && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  319. {
  320. CutToClipBuffer();
  321. }
  322. else if (e.Key == Key.C && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  323. {
  324. CopyToClipBuffer();
  325. }
  326. else if (e.Key == Key.V && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  327. {
  328. PasteFromClipBuffer();
  329. }
  330. else if (e.Key == Key.Escape)
  331. {
  332. ResetClipBuffer();
  333. InvalidateGrid();
  334. }
  335. }
  336. }
  337. void IDynamicGridUIComponentParent.DoubleClickCell(CoreRow? row, DynamicColumnBase? column)
  338. {
  339. var args = new DynamicGridCellClickEventArgs(row, column);
  340. if (OnCellDoubleClick is not null)
  341. {
  342. OnCellDoubleClick?.Invoke(this, args);
  343. if (args.Handled)
  344. return;
  345. }
  346. if (row is not null)
  347. DoDoubleClick(this, args);
  348. }
  349. void IDynamicGridUIComponentParent.ExecuteActionColumn(DynamicActionColumn column, CoreRow[]? rows)
  350. {
  351. var bRefresh = false;
  352. if(rows is null)
  353. {
  354. bRefresh = column.Action?.Invoke(null) ?? false;
  355. }
  356. else
  357. {
  358. foreach (var row in rows)
  359. if (column.Action?.Invoke(row) == true)
  360. bRefresh = true;
  361. }
  362. if (bRefresh)
  363. Dispatcher.BeginInvoke(() => { Refresh(true, true); });
  364. }
  365. void IDynamicGridUIComponentParent.OpenColumnMenu(DynamicColumnBase column)
  366. {
  367. if(column is DynamicMenuColumn menuColumn)
  368. {
  369. menuColumn.Action?.Invoke(SelectedRows.FirstOrDefault());
  370. }
  371. else if(column is DynamicActionColumn actionColumn)
  372. {
  373. var menu = actionColumn?.ContextMenu?.Invoke(SelectedRows);
  374. if (menu != null && menu.Items.Count > 0)
  375. {
  376. menu.IsOpen = true;
  377. }
  378. }
  379. }
  380. void IDynamicGridUIComponentParent.UpdateRecordCount(int count)
  381. {
  382. Count.Content = FormatRecordCount(count);
  383. }
  384. protected virtual string FormatRecordCount(int count) => $"{count} Records";
  385. void IDynamicGridUIComponentParent.LoadColumnsMenu(ContextMenu menu)
  386. {
  387. menu.AddItem("Select Columns", null, SelectColumnsClick);
  388. LoadColumnsMenu(menu);
  389. }
  390. void IDynamicGridUIComponentParent.DragOver(object sender, DragEventArgs e)
  391. {
  392. HandleDragOver(sender, e);
  393. }
  394. void IDynamicGridUIComponentParent.Drop(object sender, DragEventArgs e)
  395. {
  396. if (!Options.DragTarget)
  397. return;
  398. if(DynamicGridUtils.TryGetDropData(e, out var entityType, out var table))
  399. {
  400. OnDragEnd(entityType, table, e);
  401. }
  402. else
  403. {
  404. HandleDragDrop(sender, e);
  405. }
  406. }
  407. void IDynamicGridUIComponentParent.DragStart(object? sender, CoreRow[] rows)
  408. {
  409. Logger.Send(LogType.Information, "", "RowDragDropController_DragStart");
  410. if (!Options.DragSource)
  411. return;
  412. OnRowsDragStart(rows);
  413. }
  414. public void UIFilterChanged(object sender) => DoFilterChanged();
  415. //void IDynamicGridUIComponentParent<T>.UIFilterChanged(object sender) => DoFilterChanged();
  416. protected virtual void DoFilterChanged()
  417. {
  418. }
  419. private Dictionary<DynamicColumnBase, IDynamicGridColumnFilter?> ColumnFilters { get; set; } = new();
  420. IDynamicGridColumnFilter? IBaseDynamicGrid.GetColumnFilter(DynamicColumnBase column) => GetColumnFilter(column);
  421. protected IDynamicGridColumnFilter? GetColumnFilter(DynamicColumnBase column)
  422. {
  423. if(!ColumnFilters.TryGetValue(column, out var filter))
  424. {
  425. filter = GenerateColumnFilter(column);
  426. ColumnFilters.Add(column, filter);
  427. }
  428. return filter;
  429. }
  430. protected virtual IDynamicGridColumnFilter? GenerateColumnFilter(DynamicColumnBase column)
  431. {
  432. if(column is DynamicGridColumn gc)
  433. {
  434. if(gc.Editor is DateTimeEditor || gc.Editor is DateEditor)
  435. {
  436. return new DateTreeDynamicGridColumnFilter(this, column);
  437. }
  438. else
  439. {
  440. return new StandardDynamicGridColumnFilter(this, column);
  441. }
  442. }
  443. else if(column is DynamicActionColumn ac)
  444. {
  445. if(ac.GetFilter is not null)
  446. {
  447. return ac.GetFilter();
  448. }
  449. else if(ac is DynamicTextColumn textColumn)
  450. {
  451. return new StandardDynamicGridColumnFilter(this, textColumn);
  452. }
  453. else
  454. {
  455. return null;
  456. }
  457. }
  458. else
  459. {
  460. return null;
  461. }
  462. }
  463. #endregion
  464. protected virtual DynamicGridRowStyleSelector GetRowStyleSelector()
  465. {
  466. return new SimpleDynamicGridRowStyleSelector<DynamicGridRowStyle>();
  467. }
  468. protected virtual DynamicGridStyle GetRowStyle(CoreRow row, DynamicGridStyle style)
  469. {
  470. DynamicGridStyle? result = null;
  471. if (ClipBuffer != null)
  472. if (ClipBuffer.Item2.Contains(row))
  473. {
  474. var bgbrush = style.Background as SolidColorBrush;
  475. var bgcolor = bgbrush != null ? bgbrush.Color : Colors.Transparent;
  476. result = new DynamicGridRowStyle(style);
  477. result.Background = ClipBuffer.Item1 == ClipAction.Cut
  478. ? new SolidColorBrush(bgcolor.MixColors(0.5, Colors.Orchid))
  479. : new SolidColorBrush(bgcolor.MixColors(0.5, Colors.LightGreen));
  480. result.Foreground = new SolidColorBrush(Colors.Gray);
  481. result.FontStyle = FontStyles.Italic;
  482. }
  483. result ??= OnGetRowStyle != null ? OnGetRowStyle(row, style) : style;
  484. return result;
  485. }
  486. protected virtual void BeforeSelection(CancelEventArgs cancel)
  487. {
  488. OnBeforeSelection?.Invoke(cancel);
  489. }
  490. public bool IsReady { get; protected set; }
  491. public UIElement? Header
  492. {
  493. get => _header;
  494. set
  495. {
  496. if (_header is not null && Layout.Children.Contains(_header))
  497. Layout.Children.Remove(_header);
  498. _header = value;
  499. if (_header is not null)
  500. {
  501. _header.SetValue(Grid.RowProperty, 0);
  502. _header.SetValue(Grid.ColumnProperty, 0);
  503. _header.SetValue(Grid.ColumnSpanProperty, 2);
  504. Layout.Children.Add(_header);
  505. }
  506. }
  507. }
  508. /// <summary>
  509. /// Represents the unfiltered data in the grid. This is <see langword="null"/> until <see cref="Refresh(bool, bool)"/> is called.
  510. /// </summary>
  511. /// <remarks>
  512. /// This differs from <see cref="Data"/> in that <see cref="Data"/> has been filtered by <see cref="FilterRecord(CoreRow)"/>,
  513. /// whereas <see cref="MasterData"/> contains every record loaded from the database.
  514. /// </remarks>
  515. public CoreTable? MasterData { get; set; }
  516. public DynamicGridColumns VisibleColumns { get; protected set; }
  517. public DynamicActionColumns ActionColumns { get; protected set; }
  518. private List<DynamicColumnBase> ColumnList = new();
  519. IList<DynamicColumnBase> IBaseDynamicGrid.ColumnList => ColumnList;
  520. public CoreTable Data { get; set; }
  521. public double RowHeight
  522. {
  523. get => UIComponent.RowHeight;
  524. set => UIComponent.RowHeight = value;
  525. }
  526. public double HeaderHeight
  527. {
  528. get => UIComponent.HeaderRowHeight;
  529. set => UIComponent.HeaderRowHeight = value;
  530. }
  531. #region Options
  532. /// <summary>
  533. /// Initialise things like custom buttons; called once during construction.
  534. /// </summary>
  535. protected abstract void Init();
  536. protected abstract void DoReconfigure(DynamicGridOptions options);
  537. private bool _hasLoadedOptions = false;
  538. protected virtual void OptionsChanged()
  539. {
  540. var reloadColumns = false;
  541. if(Help is not null)
  542. {
  543. Help.Visibility = Options.ShowHelp ? Visibility.Visible : Visibility.Collapsed;
  544. }
  545. Add.Visibility = Options.AddRows ? Visibility.Visible : Visibility.Collapsed;
  546. Edit.Visibility = Options.EditRows ? Visibility.Visible : Visibility.Collapsed;
  547. EditSpacer.Visibility = Options.AddRows || Options.EditRows
  548. ? Visibility.Visible
  549. : Visibility.Collapsed;
  550. Print.Visibility = Options.Print ? Visibility.Visible : Visibility.Collapsed;
  551. PrintSpacer.Visibility = Options.Print ? Visibility.Visible : Visibility.Collapsed;
  552. Copy.Visibility = Options.ReorderRows ? Visibility.Visible : Visibility.Collapsed;
  553. ClipboardSpacer.Visibility = Options.ReorderRows ? Visibility.Visible : Visibility.Collapsed;
  554. if(ExportButton is not null)
  555. {
  556. ExportButton.Visibility = Options.ExportData ? Visibility.Visible : Visibility.Collapsed;
  557. }
  558. if(ImportButton is not null)
  559. {
  560. ImportButton.Visibility = Options.ImportData ? Visibility.Visible : Visibility.Collapsed;
  561. }
  562. ExportSpacer.Visibility = Options.ExportData || Options.ImportData
  563. ? Visibility.Visible
  564. : Visibility.Collapsed;
  565. SwitchViewBtn.Visibility = Options.DirectEdit
  566. ? Options.HideDirectEditButton
  567. ? Visibility.Collapsed
  568. : Visibility.Visible
  569. : Visibility.Collapsed;
  570. Count.Visibility = Options.RecordCount ? Visibility.Visible : Visibility.Collapsed;
  571. Delete.Visibility = Options.DeleteRows ? Visibility.Visible : Visibility.Collapsed;
  572. if (drag is not null)
  573. {
  574. var hasSequence = drag.Position == DynamicActionColumnPosition.Start;
  575. if (Options.ReorderRows)
  576. {
  577. if (!ActionColumns.Contains(drag))
  578. {
  579. ActionColumns.Insert(0, drag);
  580. }
  581. }
  582. else
  583. {
  584. ActionColumns.Remove(drag);
  585. }
  586. if(hasSequence != Options.ReorderRows)
  587. {
  588. drag.Position = Options.ReorderRows ? DynamicActionColumnPosition.Start : DynamicActionColumnPosition.Hidden;
  589. reloadColumns = true;
  590. }
  591. }
  592. if (DuplicateBtn != null)
  593. DuplicateBtn.Visibility = Visibility.Collapsed;
  594. if (UIComponent.OptionsChanged())
  595. {
  596. reloadColumns = true;
  597. }
  598. if(reloadColumns && IsReady)
  599. {
  600. Refresh(true, false);
  601. }
  602. }
  603. public bool IsDirectEditMode()
  604. {
  605. return Options.DirectEdit
  606. && (Settings.ViewMode == DynamicGridSettings.DynamicGridViewMode.DirectEdit
  607. || Settings.ViewMode == DynamicGridSettings.DynamicGridViewMode.Default);
  608. }
  609. private void SwitchView_Click(object sender, RoutedEventArgs e)
  610. {
  611. Settings.ViewMode = Settings.ViewMode switch
  612. {
  613. DynamicGridSettings.DynamicGridViewMode.Default => DynamicGridSettings.DynamicGridViewMode.Normal,
  614. DynamicGridSettings.DynamicGridViewMode.Normal => DynamicGridSettings.DynamicGridViewMode.DirectEdit,
  615. DynamicGridSettings.DynamicGridViewMode.DirectEdit or _ => DynamicGridSettings.DynamicGridViewMode.Normal
  616. };
  617. SaveSettings(Settings);
  618. Reconfigure();
  619. }
  620. public DynamicGridOptions Options { get; }
  621. protected void OnReconfigureEvent(DynamicGridOptions options)
  622. {
  623. _onReconfigure?.Invoke(options);
  624. }
  625. /// <summary>
  626. /// Configure custom buttons and options.
  627. /// </summary>
  628. public void Reconfigure(DynamicGridOptions options)
  629. {
  630. options.BeginUpdate().Clear();
  631. DoReconfigure(options);
  632. OnReconfigureEvent(options);
  633. options.EndUpdate();
  634. if (!_hasLoadedOptions)
  635. {
  636. _hasLoadedOptions = true;
  637. OptionsChanged();
  638. }
  639. }
  640. public void Reconfigure()
  641. {
  642. Reconfigure(Options);
  643. }
  644. public void Reconfigure(IDynamicGrid.ReconfigureEvent onReconfigure)
  645. {
  646. OnReconfigure += onReconfigure;
  647. Reconfigure();
  648. }
  649. #endregion
  650. protected virtual DynamicGridSettings LoadSettings()
  651. {
  652. return new DynamicGridSettings();
  653. }
  654. protected virtual void SaveSettings(DynamicGridSettings settings)
  655. {
  656. }
  657. protected virtual void LoadColumnsMenu(ContextMenu menu)
  658. {
  659. }
  660. protected void UpdateCell(int row, string colname, object? value)
  661. {
  662. var coreRow = Data.Rows[row];
  663. coreRow[colname] = value;
  664. UIComponent.UpdateCell(coreRow, colname, value);
  665. }
  666. protected void UpdateCell(CoreRow row, DynamicColumnBase column)
  667. {
  668. UIComponent.UpdateCell(row, column);
  669. }
  670. #region Row Selections
  671. protected CoreRow[] GetVisibleRows()
  672. {
  673. return UIComponent.GetVisibleRows();
  674. }
  675. public CoreRow[] SelectedRows
  676. {
  677. get => UIComponent.SelectedRows;
  678. set => UIComponent.SelectedRows = value;
  679. }
  680. /// <summary>
  681. /// Call the <see cref="OnSelectItem"/> event, and do any updating which needs to occur when items are selected.
  682. /// </summary>
  683. /// <param name="rows"></param>
  684. protected virtual void SelectItems(CoreRow[]? rows)
  685. {
  686. if (IsReady)
  687. OnSelectItem?.Invoke(this, new DynamicGridSelectionEventArgs(rows));
  688. if(DuplicateBtn is not null)
  689. {
  690. DuplicateBtn.Visibility = CanDuplicate && rows != null && rows.Length >= 1 ? Visibility.Visible : Visibility.Collapsed;
  691. }
  692. }
  693. protected virtual void DoDoubleClick(object sender, DynamicGridCellClickEventArgs args)
  694. {
  695. if (IsDirectEditMode())
  696. return;
  697. //SelectItems(SelectedRows);
  698. var e = new HandledEventArgs(false);
  699. OnDoubleClick?.Invoke(sender, e);
  700. if (e.Handled)
  701. return;
  702. if (Options.EditRows)
  703. DoEdit();
  704. }
  705. #endregion
  706. #region Column Handling
  707. #region Column Grouping
  708. public DynamicGridColumnGroupings ColumnGroupings { get; set; }
  709. /// <summary>
  710. /// Create a new column header group, and return it for editing.
  711. /// </summary>
  712. /// <returns></returns>
  713. public DynamicGridColumnGrouping AddColumnGrouping()
  714. {
  715. var group = new DynamicGridColumnGrouping();
  716. ColumnGroupings.Add(group);
  717. return group;
  718. }
  719. /// <summary>
  720. /// Gets the current column header group, and if there is none, create a new one.
  721. /// </summary>
  722. /// <returns></returns>
  723. public DynamicGridColumnGrouping GetColumnGrouping()
  724. {
  725. if(ColumnGroupings.Count == 0)
  726. {
  727. return AddColumnGrouping();
  728. }
  729. return ColumnGroupings[^1];
  730. }
  731. #endregion
  732. protected virtual DynamicGridColumns LoadColumns()
  733. {
  734. return GenerateColumns();
  735. }
  736. /// <summary>
  737. /// Provide a set of columns which is the default for this grid.
  738. /// </summary>
  739. public abstract DynamicGridColumns GenerateColumns();
  740. protected abstract void SaveColumns(DynamicGridColumns columns);
  741. public int DesiredWidth()
  742. {
  743. return UIComponent.DesiredWidth();
  744. }
  745. /// <summary>
  746. /// Handle to configure column groups.
  747. /// </summary>
  748. /// <remarks>
  749. /// This is called after <see cref="LoadColumns"/>, so by the time this is called, both <see cref="VisibleColumns"/>
  750. /// and <see cref="ActionColumns"/> will be loaded, which means one can reference these in the column groups.
  751. /// <br/>
  752. /// <b>Note:</b> <see cref="ColumnGroupings"/> is cleared before this function is called.
  753. /// </remarks>
  754. protected virtual void ConfigureColumnGroups()
  755. {
  756. }
  757. protected virtual void ConfigureColumns(DynamicGridColumns columns)
  758. {
  759. }
  760. public class ColumnsLoadedEventArgs : EventArgs
  761. {
  762. public List<DynamicColumnBase> Columns { get; private set; }
  763. public DynamicGridColumnGroupings ColumnGroupings { get; private set; }
  764. public IEnumerable<DynamicActionColumn> ActionColumns => Columns.OfType<DynamicActionColumn>();
  765. public IEnumerable<DynamicGridColumn> DataColumns => Columns.OfType<DynamicGridColumn>();
  766. public ColumnsLoadedEventArgs(List<DynamicColumnBase> columns, DynamicGridColumnGroupings columnGroupings)
  767. {
  768. Columns = columns;
  769. ColumnGroupings = columnGroupings;
  770. }
  771. public DynamicGridColumn Add<T>(
  772. Expression<Func<T, object?>> member,
  773. int? width = null,
  774. string? caption = null,
  775. string? format = null,
  776. Alignment? alignment = null)
  777. {
  778. var col = DynamicGridColumns.CreateColumn(member, width: width, caption: caption, format: format, alignment: alignment);
  779. Columns.Add(col);
  780. return col;
  781. }
  782. }
  783. public delegate void ColumnsLoadedEvent(BaseDynamicGrid sender, ColumnsLoadedEventArgs args);
  784. public event ColumnsLoadedEvent? ColumnsLoaded;
  785. protected virtual void OnColumnsLoaded(List<DynamicColumnBase> columns, DynamicGridColumnGroupings groupings)
  786. {
  787. ColumnsLoaded?.Invoke(this, new ColumnsLoadedEventArgs(columns, groupings));
  788. }
  789. private void ReloadColumns()
  790. {
  791. ColumnFilters.Clear();
  792. VisibleColumns = LoadColumns();
  793. ConfigureColumns(VisibleColumns);
  794. ColumnGroupings.Clear();
  795. ConfigureColumnGroups();
  796. ColumnList = new List<DynamicColumnBase>();
  797. ColumnList.AddRange(ActionColumns.Where(x => x.Position == DynamicActionColumnPosition.Start));
  798. ColumnList.AddRange(VisibleColumns);
  799. ColumnList.AddRange(ActionColumns.Where(x => x.Position == DynamicActionColumnPosition.End));
  800. OnColumnsLoaded(ColumnList, ColumnGroupings);
  801. UIComponent.RefreshColumns(ColumnList, ColumnGroupings);
  802. }
  803. #endregion
  804. #region Refresh / Reload
  805. protected bool IsPaging { get; set; } = false;
  806. protected virtual bool FilterRecord(CoreRow row)
  807. {
  808. if (OnFilterRecord is not null)
  809. return OnFilterRecord(row);
  810. return true;
  811. }
  812. private class RowRange(int rowIdx, int size)
  813. {
  814. public int RowIdx { get; set; } = rowIdx;
  815. public int Size { get; set; } = size;
  816. }
  817. protected abstract void ReloadData(CancellationToken token, Action<CoreTable?, Exception?> action);
  818. private CancellationTokenSource? RefreshCancellationToken;
  819. public virtual void Refresh(bool reloadcolumns, bool reloaddata)
  820. {
  821. if (bRefreshing)
  822. return;
  823. if (!DoBeforeRefresh())
  824. return;
  825. UIComponent.BeforeRefresh();
  826. using var cursor = UseWaitCursor ? new WaitCursor() : null;
  827. Loading.Visibility = Visibility.Visible;
  828. Loading.BeginAnimation(Label.OpacityProperty, LoadingFader);
  829. bRefreshing = true;
  830. if (reloadcolumns)
  831. {
  832. ReloadColumns();
  833. }
  834. if (reloaddata)
  835. {
  836. RefreshCancellationToken?.Cancel();
  837. var tokenSource = new CancellationTokenSource();
  838. RefreshCancellationToken = tokenSource;
  839. var token = tokenSource.Token;
  840. ReloadData(token, (table, exception) =>
  841. {
  842. if (token.IsCancellationRequested) return; // Don't bother even checking exceptions if task was cancelled.
  843. if (exception != null)
  844. {
  845. Dispatcher.Invoke(() =>
  846. {
  847. MessageWindow.ShowError("Sorry! We couldn't load the data.", exception);
  848. });
  849. }
  850. else if (table is not null)
  851. {
  852. if (table.Offset == 0 || MasterData is null)
  853. {
  854. MasterData = table;
  855. Dispatcher.Invoke(() =>
  856. {
  857. try
  858. {
  859. ProcessData(null);
  860. }
  861. catch (Exception)
  862. {
  863. }
  864. DoAfterRefresh();
  865. bRefreshing = false;
  866. IsReady = true;
  867. });
  868. }
  869. else
  870. {
  871. int idx = MasterData.Rows.Count;
  872. MasterData.AddPage(table);
  873. Dispatcher.Invoke(() =>
  874. {
  875. try
  876. {
  877. ProcessData(new(idx, table.Rows.Count));
  878. }
  879. catch (Exception)
  880. {
  881. }
  882. });
  883. }
  884. }
  885. });
  886. }
  887. else
  888. {
  889. ProcessData(null);
  890. DoAfterRefresh();
  891. bRefreshing = false;
  892. IsReady = true;
  893. }
  894. }
  895. public void Shutdown()
  896. {
  897. RefreshCancellationToken?.Cancel();
  898. }
  899. protected void NotifyBeforeRefresh(BeforeRefreshEventArgs args) => BeforeRefresh?.Invoke(this, args);
  900. protected void NotifyAfterRefresh(AfterRefreshEventArgs args) => AfterRefresh?.Invoke(this, args);
  901. protected bool OnBeforeRefresh()
  902. {
  903. return true;
  904. }
  905. private bool DoBeforeRefresh()
  906. {
  907. var result = OnBeforeRefresh();
  908. if (result)
  909. {
  910. var args = new BeforeRefreshEventArgs() { Cancel = false };
  911. NotifyBeforeRefresh(args);
  912. result = args.Cancel == false;
  913. }
  914. return result;
  915. }
  916. protected virtual void OnAfterRefresh()
  917. {
  918. }
  919. protected void DoAfterRefresh()
  920. {
  921. OnAfterRefresh();
  922. NotifyAfterRefresh(new AfterRefreshEventArgs());
  923. }
  924. /// <summary>
  925. /// Process the data from <see cref="MasterData"/> according to <paramref name="range"/>.
  926. /// </summary>
  927. /// <remarks>
  928. /// Set <paramref name="range"/> to <see langword="null"/> if this is the first page of data to be loaded. This will thus update the grid accordingly,
  929. /// clearing all current rows, resetting columns, selection, etc. If the <paramref name="range"/> is provided, this will add to the grid the rows
  930. /// according to the range from <see cref="MasterData"/>.
  931. /// </remarks>
  932. private void ProcessData(RowRange? range)
  933. {
  934. if(range is null)
  935. {
  936. Data.Columns.Clear();
  937. Data.Setters.Clear();
  938. if (MasterData != null)
  939. foreach (var column in MasterData.Columns)
  940. Data.Columns.Add(column);
  941. }
  942. LoadData(range);
  943. }
  944. protected readonly Dictionary<CoreRow, CoreRow> _recordmap = new();
  945. public void UpdateRow<TRow, TType>(CoreRow row, Expression<Func<TRow, TType>> column, TType value, bool refresh = true)
  946. {
  947. row.Set(column, value);
  948. _recordmap[row].Set(column, value);
  949. if (refresh)
  950. InvalidateRow(row);
  951. }
  952. public void UpdateRow<TType>(CoreRow row, string column, TType value, bool refresh = true)
  953. {
  954. row.Set(column, value);
  955. _recordmap[row].Set(column, value);
  956. if (refresh)
  957. InvalidateRow(row);
  958. }
  959. void IDynamicGridUIComponentParent.UpdateData(CoreRow row, string changedColumn, Dictionary<CoreColumn, object?> updates)
  960. {
  961. var result = new Dictionary<string, object?>();
  962. foreach (var (col, value) in updates)
  963. {
  964. UpdateRow(row, col.ColumnName, value, refresh: false);
  965. }
  966. }
  967. public void AddRow(CoreRow row)
  968. {
  969. if (MasterData is null) return;
  970. var masterrow = MasterData.NewRow();
  971. MasterData.FillRow(masterrow, row);
  972. Refresh(false, false);
  973. }
  974. public void DeleteRow(CoreRow row)
  975. {
  976. if (MasterData is null) return;
  977. var masterrow = _recordmap[row];
  978. MasterData.Rows.Remove(masterrow);
  979. Refresh(false, false);
  980. }
  981. /// <summary>
  982. /// Filter all given rows into <paramref name="into"/>, given that they match <paramref name="filter"/> and <see cref="FilterRecord(CoreRow)"/>.
  983. /// If <paramref name="recordMap"/> is given, also updates the map from <paramref name="from"/> to <paramref name="into"/>.
  984. /// </summary>
  985. protected IList<CoreRow> FilterRows(
  986. IEnumerable<CoreRow> from,
  987. CoreTable into,
  988. Dictionary<CoreRow, CoreRow>? recordMap = null,
  989. Func<CoreRow, bool>? filter = null)
  990. {
  991. var newRows = new List<CoreRow>();
  992. foreach (var row in from)
  993. if (FilterRecord(row) && filter?.Invoke(row) != false)
  994. {
  995. var newrow = into.NewRow();
  996. for (var i = 0; i < into.Columns.Count; i++)
  997. {
  998. var value = i < row.Values.Count ? row.Values[i] : null;
  999. if (into.Columns[i].DataType.IsNumeric())
  1000. value = into.Columns[i].DataType.IsDefault(value) ? null : value;
  1001. newrow.Values.Add(value);
  1002. }
  1003. newRows.Add(newrow);
  1004. into.Rows.Add(newrow);
  1005. recordMap?.TryAdd(newrow, row);
  1006. }
  1007. return newRows;
  1008. }
  1009. private void LoadData(RowRange? range)
  1010. {
  1011. if (MasterData is null)
  1012. return;
  1013. if(range is null)
  1014. {
  1015. ResetClipBuffer();
  1016. Data.Rows.Clear();
  1017. _recordmap.Clear();
  1018. FilterRows(MasterData.Rows, Data, _recordmap);
  1019. InvalidateGrid();
  1020. SelectedRows = Array.Empty<CoreRow>();
  1021. }
  1022. else
  1023. {
  1024. var _newRows = FilterRows(Enumerable.Range(range.RowIdx, range.Size).Select(i => MasterData.Rows[i]), Data, _recordmap);
  1025. UIComponent.AddPage(_newRows);
  1026. }
  1027. }
  1028. public void InvalidateRow(CoreRow row)
  1029. {
  1030. UIComponent.InvalidateRow(row);
  1031. }
  1032. protected void InvalidateGrid()
  1033. {
  1034. if (RowStyleSelector != null)
  1035. RowStyleSelector.Data = Data;
  1036. UIComponent.RefreshData(Data);
  1037. Loading.BeginAnimation(Label.OpacityProperty, null);
  1038. Loading.Visibility = Visibility.Collapsed;
  1039. }
  1040. public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  1041. {
  1042. UIComponent.AddVisualFilter(column, value, filtertype);
  1043. }
  1044. protected List<Tuple<string, Func<CoreRow, bool>>> GetFilterPredicates()
  1045. {
  1046. return UIComponent.GetFilterPredicates();
  1047. }
  1048. public object? GetData(CoreRow row, DynamicColumnBase column)
  1049. {
  1050. if(column is DynamicActionColumn ac)
  1051. {
  1052. return ac.Data(row);
  1053. }
  1054. else if(column is DynamicGridColumn gc)
  1055. {
  1056. return row[gc.ColumnName];
  1057. }
  1058. else
  1059. {
  1060. return null;
  1061. }
  1062. }
  1063. #endregion
  1064. #region Item Manipulation
  1065. #region Abstract/Virtual Functions
  1066. /// <summary>
  1067. /// Create a new row.
  1068. /// </summary>
  1069. protected abstract void NewRow();
  1070. /// <summary>
  1071. /// Edit <paramref name="rows"/> or create a new row and edit it. This should update the rows, and if it creates a new row,
  1072. /// it should be added to the grid.
  1073. /// </summary>
  1074. protected abstract bool EditRows(CoreRow[]? rows);
  1075. public abstract void DeleteRows(params CoreRow[] rows);
  1076. protected virtual bool CanDeleteRows(params CoreRow[] rows)
  1077. {
  1078. return true;
  1079. }
  1080. private bool DuplicateButton_Click(Button button, CoreRow[] rows)
  1081. {
  1082. return DoDuplicate(rows);
  1083. }
  1084. private bool DoDuplicate(CoreRow[] rows)
  1085. {
  1086. return this is IDuplicateDynamicGrid grid && grid.DoDuplicate(rows);
  1087. }
  1088. #endregion
  1089. #region Load/Save/Delete
  1090. protected virtual void DoDelete()
  1091. {
  1092. var rows = SelectedRows.ToArray();
  1093. if (rows.Any())
  1094. if (CanDeleteRows(rows))
  1095. if (MessageBox.Show("Are you sure you wish to delete the selected records?", "Confirm Delete", MessageBoxButton.YesNo) ==
  1096. MessageBoxResult.Yes)
  1097. {
  1098. DeleteRows(rows);
  1099. SelectedRows = Array.Empty<CoreRow>();
  1100. Refresh(false, true);
  1101. DoChanged();
  1102. SelectItems(null);
  1103. }
  1104. }
  1105. private void Delete_Click(object sender, RoutedEventArgs e)
  1106. {
  1107. DoDelete();
  1108. }
  1109. #endregion
  1110. #region Edit
  1111. protected virtual void DoEdit()
  1112. {
  1113. if (SelectedRows.Length == 0)
  1114. return;
  1115. if (AddEditClick(SelectedRows))
  1116. {
  1117. SelectItems(SelectedRows);
  1118. }
  1119. }
  1120. private void Edit_Click(object sender, RoutedEventArgs e)
  1121. {
  1122. DoEdit();
  1123. }
  1124. protected virtual void DoAdd(bool openEditorOnDirectEdit = false)
  1125. {
  1126. if (IsDirectEditMode() && !openEditorOnDirectEdit)
  1127. {
  1128. NewRow();
  1129. }
  1130. else if (AddEditClick(null))
  1131. {
  1132. Refresh(false, true);
  1133. }
  1134. }
  1135. private void Add_Click(object sender, RoutedEventArgs e)
  1136. {
  1137. if (CanCreateRows())
  1138. DoAdd();
  1139. }
  1140. BaseEditor IDynamicGridUIComponentParent.CustomiseEditor(DynamicGridColumn column, BaseEditor editor)
  1141. {
  1142. return editor.CloneEditor();
  1143. }
  1144. protected virtual bool CanCreateRows()
  1145. {
  1146. return true;
  1147. }
  1148. private bool AddEditClick(CoreRow[]? rows)
  1149. {
  1150. if (!IsEnabled || bRefreshing)
  1151. return false;
  1152. if (rows == null || rows.Length == 0)
  1153. {
  1154. if (!CanCreateRows())
  1155. return false;
  1156. return EditRows(null);
  1157. }
  1158. else
  1159. {
  1160. return EditRows(rows);
  1161. }
  1162. }
  1163. #endregion
  1164. protected virtual void DoPrint(object sender)
  1165. {
  1166. OnPrintData?.Invoke(sender);
  1167. }
  1168. protected virtual void ShowHelp(string slug)
  1169. {
  1170. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + slug) { UseShellExecute = true });
  1171. }
  1172. void IDynamicGridUIComponentParent.MoveRows(InABox.Core.CoreRow[] rows, int index) => MoveRows(rows, index);
  1173. #region ClipBuffer
  1174. private Tuple<ClipAction, CoreRow[]>? ClipBuffer;
  1175. protected void ResetClipBuffer()
  1176. {
  1177. ClipBuffer = null;
  1178. }
  1179. protected void SetClipBuffer(ClipAction action, CoreRow[] rows)
  1180. {
  1181. ClipBuffer = new Tuple<ClipAction, CoreRow[]>(action, rows);
  1182. }
  1183. private void CutToClipBuffer()
  1184. {
  1185. SetClipBuffer(ClipAction.Cut, SelectedRows);
  1186. InvalidateGrid();
  1187. }
  1188. private void CopyToClipBuffer()
  1189. {
  1190. SetClipBuffer(ClipAction.Copy, SelectedRows);
  1191. InvalidateGrid();
  1192. }
  1193. private void PasteFromClipBuffer()
  1194. {
  1195. if (ClipBuffer == null)
  1196. return;
  1197. var row = SelectedRows.FirstOrDefault();
  1198. MoveRows(ClipBuffer.Item2, row is not null ? (int)row.Index + 1 : Data.Rows.Count, isCopy: ClipBuffer.Item1 == ClipAction.Copy);
  1199. }
  1200. /// <summary>
  1201. /// Reorder the given rows, to place them at <paramref name="index"/>; that is, the first row of <paramref name="rows"/> will
  1202. /// be at <paramref name="index"/> after this method executes. If <paramref name="isCopy"/> is <see langword="true"/>, the items will copied, rather
  1203. /// than moved.
  1204. /// </summary>
  1205. /// <remarks>
  1206. /// To move the rows to the end, <paramref name="index"/> should be equal to the number of rows in <see cref="Data"/>.
  1207. /// </remarks>
  1208. protected abstract void MoveRows(CoreRow[] rows, int index, bool isCopy = false);
  1209. private void Copy_Click(object sender, RoutedEventArgs e)
  1210. {
  1211. var rows = SelectedRows;
  1212. if (rows.Length == 0) return;
  1213. MoveRows(rows, rows[^1].Index + 1, isCopy: true);
  1214. }
  1215. #endregion
  1216. #region Import / Export
  1217. private void DoImport()
  1218. {
  1219. if(this is IImportDynamicGrid grid)
  1220. {
  1221. grid.DoImport();
  1222. }
  1223. }
  1224. private void ImportButton_Click(object sender, RoutedEventArgs e)
  1225. {
  1226. DoImport();
  1227. }
  1228. public void Import() => DoImport();
  1229. private void DoExport()
  1230. {
  1231. if(this is IExportDynamicGrid grid)
  1232. {
  1233. grid.DoExport();
  1234. }
  1235. }
  1236. private void ExportButtonClick(object sender, RoutedEventArgs e)
  1237. {
  1238. DoExport();
  1239. }
  1240. #endregion
  1241. public void ScrollIntoView(CoreRow row)
  1242. {
  1243. UIComponent.ScrollIntoView(row);
  1244. }
  1245. #endregion
  1246. #region Custom Buttons
  1247. private Button CreateButton(BitmapImage? image = null, string? text = null, string? tooltip = null)
  1248. {
  1249. var button = new Button();
  1250. button.SetValue(BorderBrushProperty, new SolidColorBrush(Colors.Gray));
  1251. button.SetValue(BorderThicknessProperty, new Thickness(0.75));
  1252. button.Height = 30;
  1253. UpdateButton(button, image, text, tooltip);
  1254. return button;
  1255. }
  1256. public void UpdateButton(Button button, BitmapImage? image, string? text, string? tooltip = null)
  1257. {
  1258. var stackPnl = new StackPanel();
  1259. stackPnl.Orientation = Orientation.Horizontal;
  1260. //stackPnl.Margin = new Thickness(2);
  1261. if (image != null)
  1262. {
  1263. var img = new Image();
  1264. img.Source = image;
  1265. img.Margin = new Thickness(2);
  1266. img.ToolTip = tooltip;
  1267. stackPnl.Children.Add(img);
  1268. }
  1269. if (!string.IsNullOrEmpty(text))
  1270. {
  1271. button.MaxWidth = double.MaxValue;
  1272. var lbl = new Label();
  1273. lbl.Content = text;
  1274. lbl.VerticalAlignment = VerticalAlignment.Stretch;
  1275. lbl.VerticalContentAlignment = VerticalAlignment.Center;
  1276. lbl.Margin = new Thickness(2, 0, 5, 0);
  1277. lbl.ToolTip = ToolTip;
  1278. stackPnl.Children.Add(lbl);
  1279. }
  1280. else
  1281. button.MaxWidth = 30;
  1282. button.Content = stackPnl;
  1283. button.ToolTip = tooltip;
  1284. }
  1285. private bool bFirstButtonAdded = true;
  1286. private bool AnyButtonsVisible()
  1287. {
  1288. if (Add.Visibility != Visibility.Collapsed)
  1289. return true;
  1290. if (Edit.Visibility != Visibility.Collapsed)
  1291. return true;
  1292. /*if (MultiEdit.Visibility != Visibility.Collapsed)
  1293. return true;*/
  1294. if (ExportButton is not null && ExportButton.Visibility != Visibility.Collapsed)
  1295. return true;
  1296. return false;
  1297. }
  1298. public Button AddButton(string? caption, BitmapImage? image, string? tooltip, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1299. {
  1300. var button = CreateButton(image, caption, tooltip);
  1301. button.Margin = position == DynamicGridButtonPosition.Right
  1302. ? new Thickness(2, 2, 0, 0)
  1303. : bFirstButtonAdded && AnyButtonsVisible()
  1304. ? new Thickness(0, 2, 0, 0)
  1305. : new Thickness(0, 2, 2, 0);
  1306. button.Padding = !String.IsNullOrWhiteSpace(caption) ? new Thickness(5, 1, 5, 1) : new Thickness(1);
  1307. button.Tag = action;
  1308. button.Click += Button_Click;
  1309. if (position == DynamicGridButtonPosition.Right)
  1310. RightButtonStack.Children.Add(button);
  1311. else
  1312. LeftButtonStack.Children.Add(button);
  1313. bFirstButtonAdded = false;
  1314. return button;
  1315. }
  1316. public Button AddButton(string? caption, BitmapImage? image, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1317. {
  1318. var result = AddButton(caption, image, null, action, position);
  1319. return result;
  1320. }
  1321. private void Button_Click(object sender, RoutedEventArgs e)
  1322. {
  1323. var button = (Button)sender;
  1324. var action = (DynamicGridButtonClickEvent)button.Tag;
  1325. //CoreRow row = (CurrentRow > -1) && (CurrentRow < Data.Rows.Count) ? Data.Rows[this.CurrentRow] : null;
  1326. if (action.Invoke(button, SelectedRows))
  1327. Refresh(false, true);
  1328. }
  1329. #endregion
  1330. #region Header Actions
  1331. protected abstract bool SelectColumns([NotNullWhen(true)] out DynamicGridColumns? columns);
  1332. private void SelectColumnsClick()
  1333. {
  1334. if (SelectColumns(out var columns))
  1335. {
  1336. VisibleColumns.Clear();
  1337. VisibleColumns.AddRange(columns);
  1338. SaveColumns(columns);
  1339. Refresh(true, true);
  1340. }
  1341. }
  1342. #endregion
  1343. #region Drag + Drop
  1344. /// <summary>
  1345. /// Handle a number of rows from a different <see cref="DynamicGrid{T}"/> being dragged into this one.
  1346. /// </summary>
  1347. /// <param name="entity">The type of entity that that the rows of <paramref name="table"/> represent.</param>
  1348. /// <param name="table">The data being dragged.</param>
  1349. /// <param name="e"></param>
  1350. protected virtual void OnDragEnd(Type entity, CoreTable table, DragEventArgs e)
  1351. {
  1352. Logger.Send(LogType.Information,"","OnDragEnd");
  1353. }
  1354. /// <summary>
  1355. /// Handle all types of items being dragged onto this grid that aren't handled by <see cref="OnDragEnd(Type, CoreTable, DragEventArgs)"/>,
  1356. /// i.e., data which is not a <see cref="CoreTable"/> from another <see cref="DynamicGrid{T}"/>
  1357. /// </summary>
  1358. /// <remarks>
  1359. /// Can be used to handle files, for example.
  1360. /// </remarks>
  1361. /// <param name="sender"></param>
  1362. /// <param name="e"></param>
  1363. protected virtual void HandleDragDrop(object sender, DragEventArgs e)
  1364. {
  1365. }
  1366. protected virtual void HandleDragOver(object sender, DragEventArgs e)
  1367. {
  1368. }
  1369. protected virtual DragDropEffects OnRowsDragStart(CoreRow[] rows)
  1370. {
  1371. return DragDropEffects.None;
  1372. }
  1373. #endregion
  1374. }
  1375. /// <summary>
  1376. /// Shows that this <see cref="BaseDynamicGrid"/> can be used to import data.
  1377. /// </summary>
  1378. public interface IImportDynamicGrid
  1379. {
  1380. void DoImport();
  1381. }
  1382. /// <summary>
  1383. /// Shows that this <see cref="BaseDynamicGrid"/> can be used to export data.
  1384. /// </summary>
  1385. public interface IExportDynamicGrid
  1386. {
  1387. void DoExport();
  1388. }
  1389. /// <summary>
  1390. /// Shows that this <see cref="BaseDynamicGrid"/> can be used to duplicate data.
  1391. /// </summary>
  1392. public interface IDuplicateDynamicGrid
  1393. {
  1394. bool DoDuplicate(CoreRow[] rows);
  1395. }
  1396. /// <summary>
  1397. /// Shows that this <see cref="BaseDynamicGrid"/> can show a help menu.
  1398. /// </summary>
  1399. public interface IHelpDynamicGrid
  1400. {
  1401. string HelpSlug();
  1402. }