BaseDynamicGrid.cs 51 KB

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