BaseDynamicGrid.cs 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735
  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. VisibleColumns.Clear();
  802. VisibleColumns.AddRange(ColumnList.OfType<DynamicGridColumn>());
  803. UIComponent.RefreshColumns(ColumnList, ColumnGroupings);
  804. }
  805. #endregion
  806. #region Refresh / Reload
  807. protected bool IsPaging { get; set; } = false;
  808. protected virtual bool FilterRecord(CoreRow row)
  809. {
  810. if (OnFilterRecord is not null)
  811. return OnFilterRecord(row);
  812. return true;
  813. }
  814. private class RowRange(int rowIdx, int size)
  815. {
  816. public int RowIdx { get; set; } = rowIdx;
  817. public int Size { get; set; } = size;
  818. }
  819. protected abstract void ReloadData(CancellationToken token, Action<CoreTable?, Exception?> action);
  820. private CancellationTokenSource? RefreshCancellationToken;
  821. public virtual void Refresh(bool reloadcolumns, bool reloaddata)
  822. {
  823. if (bRefreshing)
  824. return;
  825. if (!DoBeforeRefresh())
  826. return;
  827. UIComponent.BeforeRefresh();
  828. using var cursor = UseWaitCursor ? new WaitCursor() : null;
  829. Loading.Visibility = Visibility.Visible;
  830. Loading.BeginAnimation(Label.OpacityProperty, LoadingFader);
  831. bRefreshing = true;
  832. if (reloadcolumns)
  833. {
  834. ReloadColumns();
  835. }
  836. if (reloaddata)
  837. {
  838. RefreshCancellationToken?.Cancel();
  839. var tokenSource = new CancellationTokenSource();
  840. RefreshCancellationToken = tokenSource;
  841. var token = tokenSource.Token;
  842. ReloadData(token, (table, exception) =>
  843. {
  844. if (token.IsCancellationRequested) return; // Don't bother even checking exceptions if task was cancelled.
  845. if (exception != null)
  846. {
  847. Dispatcher.Invoke(() =>
  848. {
  849. MessageWindow.ShowError("Sorry! We couldn't load the data.", exception);
  850. });
  851. }
  852. else if (table is not null)
  853. {
  854. if (table.Offset == 0 || MasterData is null)
  855. {
  856. MasterData = table;
  857. Dispatcher.Invoke(() =>
  858. {
  859. try
  860. {
  861. ProcessData(null);
  862. }
  863. catch (Exception)
  864. {
  865. }
  866. DoAfterRefresh();
  867. bRefreshing = false;
  868. IsReady = true;
  869. });
  870. }
  871. else
  872. {
  873. int idx = MasterData.Rows.Count;
  874. MasterData.AddPage(table);
  875. Dispatcher.Invoke(() =>
  876. {
  877. try
  878. {
  879. ProcessData(new(idx, table.Rows.Count));
  880. }
  881. catch (Exception)
  882. {
  883. }
  884. });
  885. }
  886. }
  887. });
  888. }
  889. else
  890. {
  891. ProcessData(null);
  892. DoAfterRefresh();
  893. bRefreshing = false;
  894. IsReady = true;
  895. }
  896. }
  897. public void Shutdown()
  898. {
  899. RefreshCancellationToken?.Cancel();
  900. }
  901. protected void NotifyBeforeRefresh(BeforeRefreshEventArgs args) => BeforeRefresh?.Invoke(this, args);
  902. protected void NotifyAfterRefresh(AfterRefreshEventArgs args) => AfterRefresh?.Invoke(this, args);
  903. protected bool OnBeforeRefresh()
  904. {
  905. return true;
  906. }
  907. private bool DoBeforeRefresh()
  908. {
  909. var result = OnBeforeRefresh();
  910. if (result)
  911. {
  912. var args = new BeforeRefreshEventArgs() { Cancel = false };
  913. NotifyBeforeRefresh(args);
  914. result = args.Cancel == false;
  915. }
  916. return result;
  917. }
  918. protected virtual void OnAfterRefresh()
  919. {
  920. }
  921. protected void DoAfterRefresh()
  922. {
  923. OnAfterRefresh();
  924. NotifyAfterRefresh(new AfterRefreshEventArgs());
  925. }
  926. /// <summary>
  927. /// Process the data from <see cref="MasterData"/> according to <paramref name="range"/>.
  928. /// </summary>
  929. /// <remarks>
  930. /// 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,
  931. /// clearing all current rows, resetting columns, selection, etc. If the <paramref name="range"/> is provided, this will add to the grid the rows
  932. /// according to the range from <see cref="MasterData"/>.
  933. /// </remarks>
  934. private void ProcessData(RowRange? range)
  935. {
  936. if(range is null)
  937. {
  938. Data.Columns.Clear();
  939. Data.Setters.Clear();
  940. if (MasterData != null)
  941. foreach (var column in MasterData.Columns)
  942. Data.Columns.Add(column);
  943. }
  944. LoadData(range);
  945. }
  946. protected readonly Dictionary<CoreRow, CoreRow> _recordmap = new();
  947. public void UpdateRow<TRow, TType>(CoreRow row, Expression<Func<TRow, TType>> column, TType value, bool refresh = true)
  948. {
  949. row.Set(column, value);
  950. _recordmap[row].Set(column, value);
  951. if (refresh)
  952. InvalidateRow(row);
  953. }
  954. public void UpdateRow<TType>(CoreRow row, string column, TType value, bool refresh = true)
  955. {
  956. row.Set(column, value);
  957. _recordmap[row].Set(column, value);
  958. if (refresh)
  959. InvalidateRow(row);
  960. }
  961. void IDynamicGridUIComponentParent.UpdateData(CoreRow row, string changedColumn, Dictionary<CoreColumn, object?> updates)
  962. {
  963. var result = new Dictionary<string, object?>();
  964. foreach (var (col, value) in updates)
  965. {
  966. UpdateRow(row, col.ColumnName, value, refresh: false);
  967. }
  968. }
  969. public void AddRow(CoreRow row)
  970. {
  971. if (MasterData is null) return;
  972. var masterrow = MasterData.NewRow();
  973. MasterData.FillRow(masterrow, row);
  974. Refresh(false, false);
  975. }
  976. public void DeleteRow(CoreRow row)
  977. {
  978. if (MasterData is null) return;
  979. var masterrow = _recordmap[row];
  980. MasterData.Rows.Remove(masterrow);
  981. Refresh(false, false);
  982. }
  983. /// <summary>
  984. /// Filter all given rows into <paramref name="into"/>, given that they match <paramref name="filter"/> and <see cref="FilterRecord(CoreRow)"/>.
  985. /// If <paramref name="recordMap"/> is given, also updates the map from <paramref name="from"/> to <paramref name="into"/>.
  986. /// </summary>
  987. protected IList<CoreRow> FilterRows(
  988. IEnumerable<CoreRow> from,
  989. CoreTable into,
  990. Dictionary<CoreRow, CoreRow>? recordMap = null,
  991. Func<CoreRow, bool>? filter = null)
  992. {
  993. var newRows = new List<CoreRow>();
  994. foreach (var row in from)
  995. if (FilterRecord(row) && filter?.Invoke(row) != false)
  996. {
  997. var newrow = into.NewRow();
  998. for (var i = 0; i < into.Columns.Count; i++)
  999. {
  1000. var value = i < row.Values.Count ? row.Values[i] : null;
  1001. if (into.Columns[i].DataType.IsNumeric())
  1002. value = into.Columns[i].DataType.IsDefault(value) ? null : value;
  1003. newrow.Values.Add(value);
  1004. }
  1005. newRows.Add(newrow);
  1006. into.Rows.Add(newrow);
  1007. recordMap?.TryAdd(newrow, row);
  1008. }
  1009. return newRows;
  1010. }
  1011. private void LoadData(RowRange? range)
  1012. {
  1013. if (MasterData is null)
  1014. return;
  1015. if(range is null)
  1016. {
  1017. ResetClipBuffer();
  1018. Data.Rows.Clear();
  1019. _recordmap.Clear();
  1020. FilterRows(MasterData.Rows, Data, _recordmap);
  1021. InvalidateGrid();
  1022. SelectedRows = Array.Empty<CoreRow>();
  1023. }
  1024. else
  1025. {
  1026. var _newRows = FilterRows(Enumerable.Range(range.RowIdx, range.Size).Select(i => MasterData.Rows[i]), Data, _recordmap);
  1027. UIComponent.AddPage(_newRows);
  1028. }
  1029. }
  1030. public void InvalidateRow(CoreRow row)
  1031. {
  1032. UIComponent.InvalidateRow(row);
  1033. }
  1034. protected void InvalidateGrid()
  1035. {
  1036. if (RowStyleSelector != null)
  1037. RowStyleSelector.Data = Data;
  1038. UIComponent.RefreshData(Data);
  1039. Loading.BeginAnimation(Label.OpacityProperty, null);
  1040. Loading.Visibility = Visibility.Collapsed;
  1041. }
  1042. public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  1043. {
  1044. UIComponent.AddVisualFilter(column, value, filtertype);
  1045. }
  1046. protected List<Tuple<string, Func<CoreRow, bool>>> GetFilterPredicates()
  1047. {
  1048. return UIComponent.GetFilterPredicates();
  1049. }
  1050. public object? GetData(CoreRow row, DynamicColumnBase column)
  1051. {
  1052. if(column is DynamicActionColumn ac)
  1053. {
  1054. return ac.Data(row);
  1055. }
  1056. else if(column is DynamicGridColumn gc)
  1057. {
  1058. return row[gc.ColumnName];
  1059. }
  1060. else
  1061. {
  1062. return null;
  1063. }
  1064. }
  1065. #endregion
  1066. #region Item Manipulation
  1067. #region Abstract/Virtual Functions
  1068. /// <summary>
  1069. /// Create a new row.
  1070. /// </summary>
  1071. protected abstract void NewRow();
  1072. /// <summary>
  1073. /// Edit <paramref name="rows"/> or create a new row and edit it. This should update the rows, and if it creates a new row,
  1074. /// it should be added to the grid.
  1075. /// </summary>
  1076. protected abstract bool EditRows(CoreRow[]? rows);
  1077. public abstract void DeleteRows(params CoreRow[] rows);
  1078. protected virtual bool CanDeleteRows(params CoreRow[] rows)
  1079. {
  1080. return true;
  1081. }
  1082. private bool DuplicateButton_Click(Button button, CoreRow[] rows)
  1083. {
  1084. return DoDuplicate(rows);
  1085. }
  1086. private bool DoDuplicate(CoreRow[] rows)
  1087. {
  1088. return this is IDuplicateDynamicGrid grid && grid.DoDuplicate(rows);
  1089. }
  1090. #endregion
  1091. #region Load/Save/Delete
  1092. protected virtual void DoDelete()
  1093. {
  1094. var rows = SelectedRows.ToArray();
  1095. if (rows.Any())
  1096. if (CanDeleteRows(rows))
  1097. if (MessageBox.Show("Are you sure you wish to delete the selected records?", "Confirm Delete", MessageBoxButton.YesNo) ==
  1098. MessageBoxResult.Yes)
  1099. {
  1100. DeleteRows(rows);
  1101. SelectedRows = Array.Empty<CoreRow>();
  1102. Refresh(false, true);
  1103. DoChanged();
  1104. SelectItems(null);
  1105. }
  1106. }
  1107. private void Delete_Click(object sender, RoutedEventArgs e)
  1108. {
  1109. DoDelete();
  1110. }
  1111. #endregion
  1112. #region Edit
  1113. protected virtual void DoEdit()
  1114. {
  1115. if (SelectedRows.Length == 0)
  1116. return;
  1117. if (AddEditClick(SelectedRows))
  1118. {
  1119. SelectItems(SelectedRows);
  1120. }
  1121. }
  1122. private void Edit_Click(object sender, RoutedEventArgs e)
  1123. {
  1124. DoEdit();
  1125. }
  1126. protected virtual void DoAdd(bool openEditorOnDirectEdit = false)
  1127. {
  1128. if (IsDirectEditMode() && !openEditorOnDirectEdit)
  1129. {
  1130. NewRow();
  1131. }
  1132. else if (AddEditClick(null))
  1133. {
  1134. Refresh(false, true);
  1135. }
  1136. }
  1137. private void Add_Click(object sender, RoutedEventArgs e)
  1138. {
  1139. if (CanCreateRows())
  1140. DoAdd();
  1141. }
  1142. BaseEditor IDynamicGridUIComponentParent.CustomiseEditor(DynamicGridColumn column, BaseEditor editor) => CustomiseEditor(column, editor);
  1143. protected virtual BaseEditor CustomiseEditor(DynamicGridColumn column, BaseEditor editor)
  1144. {
  1145. return editor.CloneEditor();
  1146. }
  1147. protected virtual bool CanCreateRows()
  1148. {
  1149. return true;
  1150. }
  1151. private bool AddEditClick(CoreRow[]? rows)
  1152. {
  1153. if (!IsEnabled || bRefreshing)
  1154. return false;
  1155. if (rows == null || rows.Length == 0)
  1156. {
  1157. if (!CanCreateRows())
  1158. return false;
  1159. return EditRows(null);
  1160. }
  1161. else
  1162. {
  1163. return EditRows(rows);
  1164. }
  1165. }
  1166. #endregion
  1167. protected virtual void DoPrint(object sender)
  1168. {
  1169. OnPrintData?.Invoke(sender);
  1170. }
  1171. protected virtual void ShowHelp(string slug)
  1172. {
  1173. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + slug) { UseShellExecute = true });
  1174. }
  1175. void IDynamicGridUIComponentParent.MoveRows(InABox.Core.CoreRow[] rows, int index) => MoveRows(rows, index);
  1176. #region ClipBuffer
  1177. private Tuple<ClipAction, CoreRow[]>? ClipBuffer;
  1178. protected void ResetClipBuffer()
  1179. {
  1180. ClipBuffer = null;
  1181. }
  1182. protected void SetClipBuffer(ClipAction action, CoreRow[] rows)
  1183. {
  1184. ClipBuffer = new Tuple<ClipAction, CoreRow[]>(action, rows);
  1185. }
  1186. private void CutToClipBuffer()
  1187. {
  1188. SetClipBuffer(ClipAction.Cut, SelectedRows);
  1189. InvalidateGrid();
  1190. }
  1191. private void CopyToClipBuffer()
  1192. {
  1193. SetClipBuffer(ClipAction.Copy, SelectedRows);
  1194. InvalidateGrid();
  1195. }
  1196. private void PasteFromClipBuffer()
  1197. {
  1198. if (ClipBuffer == null)
  1199. return;
  1200. var row = SelectedRows.FirstOrDefault();
  1201. MoveRows(ClipBuffer.Item2, row is not null ? (int)row.Index + 1 : Data.Rows.Count, isCopy: ClipBuffer.Item1 == ClipAction.Copy);
  1202. }
  1203. /// <summary>
  1204. /// Reorder the given rows, to place them at <paramref name="index"/>; that is, the first row of <paramref name="rows"/> will
  1205. /// be at <paramref name="index"/> after this method executes. If <paramref name="isCopy"/> is <see langword="true"/>, the items will copied, rather
  1206. /// than moved.
  1207. /// </summary>
  1208. /// <remarks>
  1209. /// To move the rows to the end, <paramref name="index"/> should be equal to the number of rows in <see cref="Data"/>.
  1210. /// </remarks>
  1211. protected abstract void MoveRows(CoreRow[] rows, int index, bool isCopy = false);
  1212. private void Copy_Click(object sender, RoutedEventArgs e)
  1213. {
  1214. var rows = SelectedRows;
  1215. if (rows.Length == 0) return;
  1216. MoveRows(rows, rows[^1].Index + 1, isCopy: true);
  1217. }
  1218. #endregion
  1219. #region Import / Export
  1220. private void DoImport()
  1221. {
  1222. if(this is IImportDynamicGrid grid)
  1223. {
  1224. grid.DoImport();
  1225. }
  1226. }
  1227. private void ImportButton_Click(object sender, RoutedEventArgs e)
  1228. {
  1229. DoImport();
  1230. }
  1231. public void Import() => DoImport();
  1232. private void DoExport()
  1233. {
  1234. if(this is IExportDynamicGrid grid)
  1235. {
  1236. grid.DoExport();
  1237. }
  1238. }
  1239. private void ExportButtonClick(object sender, RoutedEventArgs e)
  1240. {
  1241. DoExport();
  1242. }
  1243. #endregion
  1244. public void ScrollIntoView(CoreRow row)
  1245. {
  1246. UIComponent.ScrollIntoView(row);
  1247. }
  1248. #endregion
  1249. #region Custom Buttons
  1250. private Button CreateButton(BitmapImage? image = null, string? text = null, string? tooltip = null)
  1251. {
  1252. var button = new Button();
  1253. button.SetValue(BorderBrushProperty, new SolidColorBrush(Colors.Gray));
  1254. button.SetValue(BorderThicknessProperty, new Thickness(0.75));
  1255. button.Height = 30;
  1256. UpdateButton(button, image, text, tooltip);
  1257. return button;
  1258. }
  1259. public void UpdateButton(Button button, BitmapImage? image, string? text, string? tooltip = null)
  1260. {
  1261. var stackPnl = new StackPanel();
  1262. stackPnl.Orientation = Orientation.Horizontal;
  1263. //stackPnl.Margin = new Thickness(2);
  1264. if (image != null)
  1265. {
  1266. var img = new Image();
  1267. img.Source = image;
  1268. img.Margin = new Thickness(2);
  1269. img.ToolTip = tooltip;
  1270. stackPnl.Children.Add(img);
  1271. }
  1272. if (!string.IsNullOrEmpty(text))
  1273. {
  1274. button.MaxWidth = double.MaxValue;
  1275. var lbl = new Label();
  1276. lbl.Content = text;
  1277. lbl.VerticalAlignment = VerticalAlignment.Stretch;
  1278. lbl.VerticalContentAlignment = VerticalAlignment.Center;
  1279. lbl.Margin = new Thickness(2, 0, 5, 0);
  1280. lbl.ToolTip = ToolTip;
  1281. stackPnl.Children.Add(lbl);
  1282. }
  1283. else
  1284. button.MaxWidth = 30;
  1285. button.Content = stackPnl;
  1286. button.ToolTip = tooltip;
  1287. }
  1288. private bool bFirstButtonAdded = true;
  1289. private bool AnyButtonsVisible()
  1290. {
  1291. if (Add.Visibility != Visibility.Collapsed)
  1292. return true;
  1293. if (Edit.Visibility != Visibility.Collapsed)
  1294. return true;
  1295. /*if (MultiEdit.Visibility != Visibility.Collapsed)
  1296. return true;*/
  1297. if (ExportButton is not null && ExportButton.Visibility != Visibility.Collapsed)
  1298. return true;
  1299. return false;
  1300. }
  1301. public Button AddButton(string? caption, BitmapImage? image, string? tooltip, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1302. {
  1303. var button = CreateButton(image, caption, tooltip);
  1304. button.Margin = position == DynamicGridButtonPosition.Right
  1305. ? new Thickness(2, 2, 0, 0)
  1306. : bFirstButtonAdded && AnyButtonsVisible()
  1307. ? new Thickness(0, 2, 0, 0)
  1308. : new Thickness(0, 2, 2, 0);
  1309. button.Padding = !String.IsNullOrWhiteSpace(caption) ? new Thickness(5, 1, 5, 1) : new Thickness(1);
  1310. button.Tag = action;
  1311. button.Click += Button_Click;
  1312. if (position == DynamicGridButtonPosition.Right)
  1313. RightButtonStack.Children.Add(button);
  1314. else
  1315. LeftButtonStack.Children.Add(button);
  1316. bFirstButtonAdded = false;
  1317. return button;
  1318. }
  1319. public Button AddButton(string? caption, BitmapImage? image, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1320. {
  1321. var result = AddButton(caption, image, null, action, position);
  1322. return result;
  1323. }
  1324. private void Button_Click(object sender, RoutedEventArgs e)
  1325. {
  1326. var button = (Button)sender;
  1327. var action = (DynamicGridButtonClickEvent)button.Tag;
  1328. //CoreRow row = (CurrentRow > -1) && (CurrentRow < Data.Rows.Count) ? Data.Rows[this.CurrentRow] : null;
  1329. if (action.Invoke(button, SelectedRows))
  1330. Refresh(false, true);
  1331. }
  1332. #endregion
  1333. #region Header Actions
  1334. protected abstract bool SelectColumns([NotNullWhen(true)] out DynamicGridColumns? columns);
  1335. private void SelectColumnsClick()
  1336. {
  1337. if (SelectColumns(out var columns))
  1338. {
  1339. VisibleColumns.Clear();
  1340. VisibleColumns.AddRange(columns);
  1341. SaveColumns(columns);
  1342. Refresh(true, true);
  1343. }
  1344. }
  1345. #endregion
  1346. #region Drag + Drop
  1347. /// <summary>
  1348. /// Handle a number of rows from a different <see cref="DynamicGrid{T}"/> being dragged into this one.
  1349. /// </summary>
  1350. /// <param name="entity">The type of entity that that the rows of <paramref name="table"/> represent.</param>
  1351. /// <param name="table">The data being dragged.</param>
  1352. /// <param name="e"></param>
  1353. protected virtual void OnDragEnd(Type entity, CoreTable table, DragEventArgs e)
  1354. {
  1355. Logger.Send(LogType.Information,"","OnDragEnd");
  1356. }
  1357. /// <summary>
  1358. /// Handle all types of items being dragged onto this grid that aren't handled by <see cref="OnDragEnd(Type, CoreTable, DragEventArgs)"/>,
  1359. /// i.e., data which is not a <see cref="CoreTable"/> from another <see cref="DynamicGrid{T}"/>
  1360. /// </summary>
  1361. /// <remarks>
  1362. /// Can be used to handle files, for example.
  1363. /// </remarks>
  1364. /// <param name="sender"></param>
  1365. /// <param name="e"></param>
  1366. protected virtual void HandleDragDrop(object sender, DragEventArgs e)
  1367. {
  1368. }
  1369. protected virtual void HandleDragOver(object sender, DragEventArgs e)
  1370. {
  1371. }
  1372. protected virtual DragDropEffects OnRowsDragStart(CoreRow[] rows)
  1373. {
  1374. return DragDropEffects.None;
  1375. }
  1376. #endregion
  1377. }
  1378. /// <summary>
  1379. /// Shows that this <see cref="BaseDynamicGrid"/> can be used to import data.
  1380. /// </summary>
  1381. public interface IImportDynamicGrid
  1382. {
  1383. void DoImport();
  1384. }
  1385. /// <summary>
  1386. /// Shows that this <see cref="BaseDynamicGrid"/> can be used to export data.
  1387. /// </summary>
  1388. public interface IExportDynamicGrid
  1389. {
  1390. void DoExport();
  1391. }
  1392. /// <summary>
  1393. /// Shows that this <see cref="BaseDynamicGrid"/> can be used to duplicate data.
  1394. /// </summary>
  1395. public interface IDuplicateDynamicGrid
  1396. {
  1397. bool DoDuplicate(CoreRow[] rows);
  1398. }
  1399. /// <summary>
  1400. /// Shows that this <see cref="BaseDynamicGrid"/> can show a help menu.
  1401. /// </summary>
  1402. public interface IHelpDynamicGrid
  1403. {
  1404. string HelpSlug();
  1405. }