BaseDynamicGrid.cs 50 KB

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