BaseDynamicGrid.cs 51 KB

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