BaseDynamicGrid.cs 54 KB

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