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 e)
  870. {
  871. CoreUtils.LogException("", e);
  872. }
  873. DoAfterRefresh();
  874. bRefreshing = false;
  875. IsReady = true;
  876. });
  877. }
  878. else
  879. {
  880. int idx = MasterData.Rows.Count;
  881. MasterData.AddPage(table);
  882. Dispatcher.Invoke(() =>
  883. {
  884. try
  885. {
  886. ProcessData(new(idx, table.Rows.Count));
  887. }
  888. catch (Exception)
  889. {
  890. }
  891. });
  892. }
  893. }
  894. });
  895. }
  896. else
  897. {
  898. ProcessData(null);
  899. DoAfterRefresh();
  900. bRefreshing = false;
  901. IsReady = true;
  902. }
  903. }
  904. public void Shutdown()
  905. {
  906. RefreshCancellationToken?.Cancel();
  907. }
  908. protected void NotifyBeforeRefresh(BeforeRefreshEventArgs args) => BeforeRefresh?.Invoke(this, args);
  909. protected void NotifyAfterRefresh(AfterRefreshEventArgs args) => AfterRefresh?.Invoke(this, args);
  910. protected bool OnBeforeRefresh()
  911. {
  912. return true;
  913. }
  914. private bool DoBeforeRefresh()
  915. {
  916. var result = OnBeforeRefresh();
  917. if (result)
  918. {
  919. var args = new BeforeRefreshEventArgs() { Cancel = false };
  920. NotifyBeforeRefresh(args);
  921. result = args.Cancel == false;
  922. }
  923. return result;
  924. }
  925. protected virtual void OnAfterRefresh()
  926. {
  927. }
  928. protected void DoAfterRefresh()
  929. {
  930. OnAfterRefresh();
  931. NotifyAfterRefresh(new AfterRefreshEventArgs());
  932. }
  933. /// <summary>
  934. /// Process the data from <see cref="MasterData"/> according to <paramref name="range"/>.
  935. /// </summary>
  936. /// <remarks>
  937. /// Set <paramref name="range"/> to <see langword="null"/> if this is the first page of data to be loaded. This will thus update the grid accordingly,
  938. /// clearing all current rows, resetting columns, selection, etc. If the <paramref name="range"/> is provided, this will add to the grid the rows
  939. /// according to the range from <see cref="MasterData"/>.
  940. /// </remarks>
  941. private void ProcessData(RowRange? range)
  942. {
  943. if(range is null)
  944. {
  945. Data.Columns.Clear();
  946. Data.Setters.Clear();
  947. if (MasterData != null)
  948. foreach (var column in MasterData.Columns)
  949. Data.Columns.Add(column);
  950. }
  951. LoadData(range);
  952. }
  953. protected readonly Dictionary<CoreRow, CoreRow> _recordmap = new();
  954. public void UpdateRow<TRow, TType>(CoreRow row, Expression<Func<TRow, TType>> column, TType value, bool refresh = true)
  955. {
  956. row.Set(column, value);
  957. _recordmap[row].Set(column, value);
  958. if (refresh)
  959. InvalidateRow(row);
  960. }
  961. public void UpdateRow<TType>(CoreRow row, string column, TType value, bool refresh = true)
  962. {
  963. row.Set(column, value);
  964. _recordmap[row].Set(column, value);
  965. if (refresh)
  966. InvalidateRow(row);
  967. }
  968. void IDynamicGridUIComponentParent.UpdateData(CoreRow row, string changedColumn, Dictionary<CoreColumn, object?> updates)
  969. {
  970. var result = new Dictionary<string, object?>();
  971. foreach (var (col, value) in updates)
  972. {
  973. UpdateRow(row, col.ColumnName, value, refresh: false);
  974. }
  975. }
  976. public void AddRow(CoreRow row)
  977. {
  978. if (MasterData is null) return;
  979. var masterrow = MasterData.NewRow();
  980. MasterData.FillRow(masterrow, row);
  981. Refresh(false, false);
  982. }
  983. public void DeleteRow(CoreRow row)
  984. {
  985. if (MasterData is null) return;
  986. var masterrow = _recordmap[row];
  987. MasterData.Rows.Remove(masterrow);
  988. Refresh(false, false);
  989. }
  990. /// <summary>
  991. /// Filter all given rows into <paramref name="into"/>, given that they match <paramref name="filter"/> and <see cref="FilterRecord(CoreRow)"/>.
  992. /// If <paramref name="recordMap"/> is given, also updates the map from <paramref name="from"/> to <paramref name="into"/>.
  993. /// </summary>
  994. protected IList<CoreRow> FilterRows(
  995. IEnumerable<CoreRow> from,
  996. CoreTable into,
  997. Dictionary<CoreRow, CoreRow>? recordMap = null,
  998. Func<CoreRow, bool>? filter = null)
  999. {
  1000. var newRows = new List<CoreRow>();
  1001. foreach (var row in from)
  1002. if (FilterRecord(row) && filter?.Invoke(row) != false)
  1003. {
  1004. var newrow = into.NewRow();
  1005. for (var i = 0; i < into.Columns.Count; i++)
  1006. {
  1007. var value = i < row.Values.Count ? row.Values[i] : null;
  1008. if (into.Columns[i].DataType.IsNumeric())
  1009. value = into.Columns[i].DataType.IsDefault(value) ? null : value;
  1010. newrow.Values.Add(value);
  1011. }
  1012. newRows.Add(newrow);
  1013. into.Rows.Add(newrow);
  1014. recordMap?.TryAdd(newrow, row);
  1015. }
  1016. return newRows;
  1017. }
  1018. private void LoadData(RowRange? range)
  1019. {
  1020. if (MasterData is null)
  1021. return;
  1022. if(range is null)
  1023. {
  1024. ResetClipBuffer();
  1025. Data.Rows.Clear();
  1026. _recordmap.Clear();
  1027. FilterRows(MasterData.Rows, Data, _recordmap);
  1028. InvalidateGrid();
  1029. SelectedRows = Array.Empty<CoreRow>();
  1030. }
  1031. else
  1032. {
  1033. var _newRows = FilterRows(Enumerable.Range(range.RowIdx, range.Size).Select(i => MasterData.Rows[i]), Data, _recordmap);
  1034. UIComponent.AddPage(_newRows);
  1035. }
  1036. }
  1037. public void InvalidateRow(CoreRow row)
  1038. {
  1039. UIComponent.InvalidateRow(row);
  1040. }
  1041. protected void InvalidateGrid()
  1042. {
  1043. if (RowStyleSelector != null)
  1044. RowStyleSelector.Data = Data;
  1045. UIComponent.RefreshData(Data);
  1046. Loading.BeginAnimation(Label.OpacityProperty, null);
  1047. Loading.Visibility = Visibility.Collapsed;
  1048. }
  1049. public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  1050. {
  1051. UIComponent.AddVisualFilter(column, value, filtertype);
  1052. }
  1053. protected List<Tuple<string, Func<CoreRow, bool>>> GetFilterPredicates()
  1054. {
  1055. return UIComponent.GetFilterPredicates();
  1056. }
  1057. public object? GetData(CoreRow row, DynamicColumnBase column)
  1058. {
  1059. if(column is DynamicActionColumn ac)
  1060. {
  1061. return ac.Data(row);
  1062. }
  1063. else if(column is DynamicGridColumn gc)
  1064. {
  1065. return row[gc.ColumnName];
  1066. }
  1067. else
  1068. {
  1069. return null;
  1070. }
  1071. }
  1072. #endregion
  1073. #region Item Manipulation
  1074. #region Abstract/Virtual Functions
  1075. /// <summary>
  1076. /// Create a new row.
  1077. /// </summary>
  1078. protected abstract void NewRow();
  1079. /// <summary>
  1080. /// Edit <paramref name="rows"/> or create a new row and edit it. This should update the rows, and if it creates a new row,
  1081. /// it should be added to the grid.
  1082. /// </summary>
  1083. protected abstract bool EditRows(CoreRow[]? rows);
  1084. public abstract void DeleteRows(params CoreRow[] rows);
  1085. protected virtual bool CanDeleteRows(params CoreRow[] rows)
  1086. {
  1087. return true;
  1088. }
  1089. private bool DuplicateButton_Click(Button button, CoreRow[] rows)
  1090. {
  1091. return DoDuplicate(rows);
  1092. }
  1093. private bool DoDuplicate(CoreRow[] rows)
  1094. {
  1095. return this is IDuplicateDynamicGrid grid && grid.DoDuplicate(rows);
  1096. }
  1097. #endregion
  1098. #region Load/Save/Delete
  1099. protected virtual void DoDelete()
  1100. {
  1101. var rows = SelectedRows.ToArray();
  1102. if (rows.Any())
  1103. if (CanDeleteRows(rows))
  1104. if (MessageBox.Show("Are you sure you wish to delete the selected records?", "Confirm Delete", MessageBoxButton.YesNo) ==
  1105. MessageBoxResult.Yes)
  1106. {
  1107. DeleteRows(rows);
  1108. SelectedRows = Array.Empty<CoreRow>();
  1109. Refresh(false, true);
  1110. DoChanged();
  1111. SelectItems(null);
  1112. }
  1113. }
  1114. private void Delete_Click(object sender, RoutedEventArgs e)
  1115. {
  1116. DoDelete();
  1117. }
  1118. #endregion
  1119. #region Edit
  1120. protected virtual void DoEdit()
  1121. {
  1122. if (SelectedRows.Length == 0)
  1123. return;
  1124. if (AddEditClick(SelectedRows))
  1125. {
  1126. SelectItems(SelectedRows);
  1127. }
  1128. }
  1129. private void Edit_Click(object sender, RoutedEventArgs e)
  1130. {
  1131. DoEdit();
  1132. }
  1133. protected virtual void DoAdd(bool openEditorOnDirectEdit = false)
  1134. {
  1135. if (IsDirectEditMode() && !openEditorOnDirectEdit)
  1136. {
  1137. NewRow();
  1138. }
  1139. else if (AddEditClick(null))
  1140. {
  1141. Refresh(false, true);
  1142. }
  1143. }
  1144. private void Add_Click(object sender, RoutedEventArgs e)
  1145. {
  1146. if (CanCreateRows())
  1147. DoAdd();
  1148. }
  1149. BaseEditor IDynamicGridUIComponentParent.CustomiseEditor(DynamicGridColumn column, BaseEditor editor) => CustomiseEditor(column, editor);
  1150. protected virtual BaseEditor CustomiseEditor(DynamicGridColumn column, BaseEditor editor)
  1151. {
  1152. return editor.CloneEditor();
  1153. }
  1154. protected virtual bool CanCreateRows()
  1155. {
  1156. return true;
  1157. }
  1158. private bool AddEditClick(CoreRow[]? rows)
  1159. {
  1160. if (!IsEnabled || bRefreshing)
  1161. return false;
  1162. if (rows == null || rows.Length == 0)
  1163. {
  1164. if (!CanCreateRows())
  1165. return false;
  1166. return EditRows(null);
  1167. }
  1168. else
  1169. {
  1170. return EditRows(rows);
  1171. }
  1172. }
  1173. #endregion
  1174. protected virtual void DoPrint(object sender)
  1175. {
  1176. OnPrintData?.Invoke(sender);
  1177. }
  1178. protected virtual void ShowHelp(string slug)
  1179. {
  1180. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + slug) { UseShellExecute = true });
  1181. }
  1182. void IDynamicGridUIComponentParent.MoveRows(InABox.Core.CoreRow[] rows, int index) => MoveRows(rows, index);
  1183. #region ClipBuffer
  1184. private Tuple<ClipAction, CoreRow[]>? ClipBuffer;
  1185. protected void ResetClipBuffer()
  1186. {
  1187. ClipBuffer = null;
  1188. }
  1189. protected void SetClipBuffer(ClipAction action, CoreRow[] rows)
  1190. {
  1191. ClipBuffer = new Tuple<ClipAction, CoreRow[]>(action, rows);
  1192. }
  1193. private void CutToClipBuffer()
  1194. {
  1195. SetClipBuffer(ClipAction.Cut, SelectedRows);
  1196. InvalidateGrid();
  1197. }
  1198. private void CopyToClipBuffer()
  1199. {
  1200. SetClipBuffer(ClipAction.Copy, SelectedRows);
  1201. InvalidateGrid();
  1202. }
  1203. private void PasteFromClipBuffer()
  1204. {
  1205. if (ClipBuffer == null)
  1206. return;
  1207. var row = SelectedRows.FirstOrDefault();
  1208. MoveRows(ClipBuffer.Item2, row is not null ? (int)row.Index + 1 : Data.Rows.Count, isCopy: ClipBuffer.Item1 == ClipAction.Copy);
  1209. }
  1210. /// <summary>
  1211. /// Reorder the given rows, to place them at <paramref name="index"/>; that is, the first row of <paramref name="rows"/> will
  1212. /// be at <paramref name="index"/> after this method executes. If <paramref name="isCopy"/> is <see langword="true"/>, the items will copied, rather
  1213. /// than moved.
  1214. /// </summary>
  1215. /// <remarks>
  1216. /// To move the rows to the end, <paramref name="index"/> should be equal to the number of rows in <see cref="Data"/>.
  1217. /// </remarks>
  1218. protected abstract void MoveRows(CoreRow[] rows, int index, bool isCopy = false);
  1219. private void Copy_Click(object sender, RoutedEventArgs e)
  1220. {
  1221. var rows = SelectedRows;
  1222. if (rows.Length == 0) return;
  1223. MoveRows(rows, rows[^1].Index + 1, isCopy: true);
  1224. }
  1225. #endregion
  1226. #region Import / Export
  1227. private void DoImport()
  1228. {
  1229. if(this is IImportDynamicGrid grid)
  1230. {
  1231. grid.DoImport();
  1232. }
  1233. }
  1234. private void ImportButton_Click(object sender, RoutedEventArgs e)
  1235. {
  1236. DoImport();
  1237. }
  1238. public void Import() => DoImport();
  1239. private void DoExport()
  1240. {
  1241. if(this is IExportDynamicGrid grid)
  1242. {
  1243. grid.DoExport();
  1244. }
  1245. }
  1246. private void ExportButtonClick(object sender, RoutedEventArgs e)
  1247. {
  1248. DoExport();
  1249. }
  1250. #endregion
  1251. public void ScrollIntoView(CoreRow row)
  1252. {
  1253. UIComponent.ScrollIntoView(row);
  1254. }
  1255. #endregion
  1256. #region Custom Buttons
  1257. private Button CreateButton(ImageSource? image = null, string? text = null, string? tooltip = null)
  1258. {
  1259. var button = new Button();
  1260. button.SetValue(BorderBrushProperty, new SolidColorBrush(Colors.Gray));
  1261. button.SetValue(BorderThicknessProperty, new Thickness(0.75));
  1262. button.Height = 30;
  1263. button.MinWidth = 30;
  1264. UpdateButton(button, image, text, tooltip);
  1265. return button;
  1266. }
  1267. public void UpdateButton(Button button, ImageSource? image, string? text, string? tooltip = null)
  1268. {
  1269. var stackPnl = new StackPanel();
  1270. stackPnl.Orientation = Orientation.Horizontal;
  1271. //stackPnl.Margin = new Thickness(2);
  1272. if (image != null)
  1273. {
  1274. var img = new Image();
  1275. img.Source = image;
  1276. img.Margin = new Thickness(2);
  1277. img.ToolTip = tooltip;
  1278. stackPnl.Children.Add(img);
  1279. }
  1280. if (!string.IsNullOrEmpty(text))
  1281. {
  1282. button.MaxWidth = double.MaxValue;
  1283. var lbl = new Label();
  1284. lbl.Content = text;
  1285. lbl.VerticalAlignment = VerticalAlignment.Stretch;
  1286. lbl.VerticalContentAlignment = VerticalAlignment.Center;
  1287. lbl.Margin = new Thickness(2, 0, 5, 0);
  1288. lbl.ToolTip = ToolTip;
  1289. stackPnl.Children.Add(lbl);
  1290. }
  1291. else
  1292. button.MaxWidth = 30;
  1293. button.Content = stackPnl;
  1294. button.ToolTip = tooltip;
  1295. }
  1296. private bool bFirstButtonAdded = true;
  1297. private bool AnyButtonsVisible()
  1298. {
  1299. if (Add.Visibility != Visibility.Collapsed)
  1300. return true;
  1301. if (Edit.Visibility != Visibility.Collapsed)
  1302. return true;
  1303. /*if (MultiEdit.Visibility != Visibility.Collapsed)
  1304. return true;*/
  1305. if (ExportButton is not null && ExportButton.Visibility != Visibility.Collapsed)
  1306. return true;
  1307. return false;
  1308. }
  1309. public Button AddButton(string? caption, ImageSource? image, string? tooltip, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1310. {
  1311. var button = CreateButton(image, caption, tooltip);
  1312. button.Margin = position == DynamicGridButtonPosition.Right
  1313. ? new Thickness(2, 2, 0, 0)
  1314. : bFirstButtonAdded && AnyButtonsVisible()
  1315. ? new Thickness(0, 2, 0, 0)
  1316. : new Thickness(0, 2, 2, 0);
  1317. button.Padding = !String.IsNullOrWhiteSpace(caption) ? new Thickness(5, 1, 5, 1) : new Thickness(1);
  1318. button.Tag = action;
  1319. button.Click += Button_Click;
  1320. if (position == DynamicGridButtonPosition.Right)
  1321. RightButtonStack.Children.Add(button);
  1322. else
  1323. LeftButtonStack.Children.Add(button);
  1324. bFirstButtonAdded = false;
  1325. return button;
  1326. }
  1327. public Button AddButton(string? caption, ImageSource? image, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1328. {
  1329. var result = AddButton(caption, image, null, action, position);
  1330. return result;
  1331. }
  1332. private void Button_Click(object sender, RoutedEventArgs e)
  1333. {
  1334. var button = (Button)sender;
  1335. var action = (DynamicGridButtonClickEvent)button.Tag;
  1336. //CoreRow row = (CurrentRow > -1) && (CurrentRow < Data.Rows.Count) ? Data.Rows[this.CurrentRow] : null;
  1337. if (action.Invoke(button, SelectedRows))
  1338. Refresh(false, true);
  1339. }
  1340. #endregion
  1341. #region Header Actions
  1342. protected abstract bool SelectColumns([NotNullWhen(true)] out DynamicGridColumns? columns);
  1343. private void SelectColumnsClick()
  1344. {
  1345. if (SelectColumns(out var columns))
  1346. {
  1347. VisibleColumns.Clear();
  1348. VisibleColumns.AddRange(columns);
  1349. SaveColumns(columns);
  1350. Refresh(true, true);
  1351. }
  1352. }
  1353. #endregion
  1354. #region Drag + Drop
  1355. /// <summary>
  1356. /// Handle a number of rows from a different <see cref="DynamicGrid{T}"/> being dragged into this one.
  1357. /// </summary>
  1358. /// <param name="entity">The type of entity that that the rows of <paramref name="table"/> represent.</param>
  1359. /// <param name="table">The data being dragged.</param>
  1360. /// <param name="e"></param>
  1361. protected virtual void OnDragEnd(Type entity, CoreTable table, DragEventArgs e)
  1362. {
  1363. Logger.Send(LogType.Information,"","OnDragEnd");
  1364. }
  1365. /// <summary>
  1366. /// Handle all types of items being dragged onto this grid that aren't handled by <see cref="OnDragEnd(Type, CoreTable, DragEventArgs)"/>,
  1367. /// i.e., data which is not a <see cref="CoreTable"/> from another <see cref="DynamicGrid{T}"/>
  1368. /// </summary>
  1369. /// <remarks>
  1370. /// Can be used to handle files, for example.
  1371. /// </remarks>
  1372. /// <param name="sender"></param>
  1373. /// <param name="e"></param>
  1374. protected virtual void HandleDragDrop(object sender, DragEventArgs e)
  1375. {
  1376. }
  1377. protected virtual void HandleDragOver(object sender, DragEventArgs e)
  1378. {
  1379. }
  1380. protected virtual DragDropEffects OnRowsDragStart(CoreRow[] rows)
  1381. {
  1382. return DragDropEffects.None;
  1383. }
  1384. #endregion
  1385. }
  1386. /// <summary>
  1387. /// Shows that this <see cref="BaseDynamicGrid"/> can be used to import data.
  1388. /// </summary>
  1389. public interface IImportDynamicGrid
  1390. {
  1391. void DoImport();
  1392. }
  1393. /// <summary>
  1394. /// Shows that this <see cref="BaseDynamicGrid"/> can be used to export data.
  1395. /// </summary>
  1396. public interface IExportDynamicGrid
  1397. {
  1398. void DoExport();
  1399. }
  1400. /// <summary>
  1401. /// Shows that this <see cref="BaseDynamicGrid"/> can be used to duplicate data.
  1402. /// </summary>
  1403. public interface IDuplicateDynamicGrid
  1404. {
  1405. bool DoDuplicate(CoreRow[] rows);
  1406. }
  1407. /// <summary>
  1408. /// Shows that this <see cref="BaseDynamicGrid"/> can show a help menu.
  1409. /// </summary>
  1410. public interface IHelpDynamicGrid
  1411. {
  1412. string HelpSlug();
  1413. }