BaseDynamicGrid.cs 54 KB

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