BaseDynamicGrid.cs 51 KB

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