DynamicGrid.cs 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433
  1. using System;
  2. using System.Collections.Generic;
  3. using System.ComponentModel;
  4. using System.Data;
  5. using System.Diagnostics;
  6. using System.Globalization;
  7. using System.Linq;
  8. using System.Linq.Expressions;
  9. using System.Threading.Tasks;
  10. using System.Windows;
  11. using System.Windows.Controls;
  12. using System.Windows.Data;
  13. using System.Windows.Input;
  14. using System.Windows.Media;
  15. using System.Windows.Media.Animation;
  16. using System.Windows.Media.Imaging;
  17. using InABox.Clients;
  18. using InABox.Core;
  19. using InABox.Wpf;
  20. using InABox.WPF;
  21. using Syncfusion.Data;
  22. using Syncfusion.UI.Xaml.Grid;
  23. using Syncfusion.UI.Xaml.Grid.Helpers;
  24. using static InABox.DynamicGrid.IDynamicGrid;
  25. using Color = System.Drawing.Color;
  26. using Columns = InABox.Core.Columns;
  27. using Image = System.Windows.Controls.Image;
  28. using RowColumnIndex = Syncfusion.UI.Xaml.ScrollAxis.RowColumnIndex;
  29. using SolidColorBrush = System.Windows.Media.SolidColorBrush;
  30. using String = System.String;
  31. using VerticalAlignment = System.Windows.VerticalAlignment;
  32. using VirtualizingCellsControl = Syncfusion.UI.Xaml.Grid.VirtualizingCellsControl;
  33. namespace InABox.DynamicGrid;
  34. public abstract class DynamicGrid : ContentControl
  35. {
  36. public static readonly DependencyProperty UseWaitCursorProperty =
  37. DependencyProperty.Register(nameof(UseWaitCursor), typeof(bool), typeof(DynamicGrid<>));
  38. public bool UseWaitCursor
  39. {
  40. get => (bool)GetValue(UseWaitCursorProperty);
  41. set => SetValue(UseWaitCursorProperty, value);
  42. }
  43. }
  44. public abstract class DynamicGrid<T> : DynamicGrid, IDynamicGridUIComponentParent<T>, IDynamicGrid<T>
  45. where T : BaseObject, new()
  46. {
  47. protected enum ClipAction
  48. {
  49. Cut,
  50. Copy
  51. }
  52. private IDynamicGridUIComponent<T> UIComponent { get; set; }
  53. private UIElement? _header;
  54. private readonly Button Add;
  55. public bool bRefreshing;
  56. bool IDynamicGridUIComponentParent<T>.IsRefreshing => bRefreshing;
  57. private readonly Label ClipboardSpacer;
  58. private readonly Button Copy;
  59. private readonly Label Count;
  60. private readonly Button Cut;
  61. private readonly Border Disabler;
  62. private readonly Button Delete;
  63. private readonly DockPanel Docker;
  64. private readonly DynamicRowMovementColumn? down;
  65. private readonly Button Edit;
  66. private readonly Label EditSpacer;
  67. private readonly Button Export;
  68. private readonly Label ExportSpacer;
  69. private readonly Button DuplicateBtn;
  70. private readonly Button SwitchViewBtn;
  71. private readonly Button Help;
  72. private readonly Button Import;
  73. private readonly Grid Layout;
  74. private readonly Label Loading;
  75. private DoubleAnimation LoadingFader = new DoubleAnimation(1d, 0.2d, new Duration(TimeSpan.FromSeconds(2))) { AutoReverse = true };
  76. //private readonly Button MultiEdit;
  77. private readonly Button Paste;
  78. private readonly Button Print;
  79. private readonly Label PrintSpacer;
  80. private readonly StackPanel LeftButtonStack;
  81. private readonly StackPanel RightButtonStack;
  82. private readonly DynamicRowMovementColumn? up;
  83. protected DynamicGridRowStyleSelector<T> RowStyleSelector;
  84. #region Events
  85. public event IDynamicGrid.ReconfigureEvent? OnReconfigure;
  86. public OnGetDynamicGridRowStyle? OnGetRowStyle { get; set; }
  87. public ValidateEvent<T>? OnValidate { get; set; }
  88. public event OnPrintData? OnPrintData;
  89. public event BeforeRefreshEventHandler? BeforeRefresh;
  90. public event AfterRefreshEventHandler? AfterRefresh;
  91. public event OnDefineFilter? OnDefineFilter;
  92. public event OnCreateItem? OnCreateItem;
  93. public event OnAfterCreateItem? OnAfterCreateItem;
  94. /// <summary>
  95. /// Called when an item is selected in the grid. It is not called if <see cref="IsReady"/> is not <see langword="true"/>.
  96. /// </summary>
  97. /// <remarks>
  98. /// It is unnecessary to use this if within a grid. Instead, override <see cref="SelectItems(CoreRow[]?)"/>.
  99. /// </remarks>
  100. public event SelectItemHandler? OnSelectItem;
  101. public event OnCellDoubleClick? OnCellDoubleClick;
  102. public event EventHandler? OnChanged;
  103. public delegate void BeforeSelectionEvent(CancelEventArgs cancel);
  104. public event BeforeSelectionEvent? OnBeforeSelection;
  105. protected virtual void Changed()
  106. {
  107. }
  108. public virtual void DoChanged()
  109. {
  110. Changed();
  111. OnChanged?.Invoke(this, EventArgs.Empty);
  112. }
  113. public event EditorValueChangedHandler? OnEditorValueChanged;
  114. public event OnCustomiseEditor<T>? OnCustomiseEditor;
  115. public event OnFilterRecord? OnFilterRecord;
  116. public event OnDoubleClick? OnDoubleClick;
  117. public event EntitySaveEvent? OnBeforeSave;
  118. public event EntitySaveEvent? OnAfterSave;
  119. public delegate void EditorLoaded(IDynamicEditorForm editor, T[] items);
  120. public event EditorLoaded OnEditorLoaded;
  121. public event OnLoadEditorButtons<T> OnLoadEditorButtons;
  122. #endregion
  123. protected DynamicGridSettings Settings { get; set; }
  124. public DynamicGrid() : base()
  125. {
  126. UseWaitCursor = true;
  127. Options = new DynamicGridOptions();
  128. Options.OnChanged += () =>
  129. {
  130. _hasLoadedOptions = true;
  131. OptionsChanged();
  132. };
  133. ActionColumns = new DynamicActionColumns();
  134. ColumnGroupings = new DynamicGridColumnGroupings();
  135. RowStyleSelector = GetRowStyleSelector();
  136. RowStyleSelector.GetStyle += (row, style) => GetRowStyle(row, style);
  137. IsReady = false;
  138. Data = new CoreTable();
  139. MasterColumns = new DynamicGridColumns();
  140. MasterColumns.ExtractColumns(typeof(T));
  141. HiddenColumns = new HiddenColumnsList();
  142. foreach (var column in LookupFactory.RequiredColumns<T>().ColumnNames())
  143. {
  144. AddHiddenColumn(column);
  145. }
  146. if (ShowSequenceButtons)
  147. {
  148. up = new DynamicRowMovementColumn(DynamicRowMovement.Up, SwapRows);
  149. ActionColumns.Add(up);
  150. down = new DynamicRowMovementColumn(DynamicRowMovement.Down, SwapRows);
  151. ActionColumns.Add(down);
  152. HiddenColumns.Add(x => (x as ISequenceable)!.Sequence);
  153. }
  154. VisibleColumns = new DynamicGridColumns();
  155. UIComponent = CreateUIComponent();
  156. Loading = new Label();
  157. Loading.Content = "Loading...";
  158. Loading.Foreground = new SolidColorBrush(Colors.White);
  159. Loading.VerticalContentAlignment = VerticalAlignment.Center;
  160. Loading.HorizontalContentAlignment = HorizontalAlignment.Center;
  161. Loading.Visibility = Visibility.Collapsed;
  162. Loading.SetValue(Panel.ZIndexProperty, 999);
  163. Loading.SetValue(Grid.RowProperty, 1);
  164. Loading.FontSize = 14.0F;
  165. LoadingFader.Completed += (sender, args) =>
  166. {
  167. if (Loading.Visibility == Visibility.Visible)
  168. {
  169. //Logger.Send(LogType.Information, this.GetType().EntityName().Split(".").Last(), "Loading Fader Restarting");
  170. Loading.BeginAnimation(Label.OpacityProperty, LoadingFader);
  171. }
  172. };
  173. Help = CreateButton(Wpf.Resources.help.AsBitmapImage(Color.White));
  174. Help.Margin = new Thickness(0, 2, 2, 0);
  175. Help.SetValue(DockPanel.DockProperty, Dock.Right);
  176. Help.Click += (o, e) => ShowHelp(typeof(T).Name.Split('.').Last().SplitCamelCase().Replace(" ", "_"));
  177. Add = CreateButton(Wpf.Resources.add.AsBitmapImage(Color.White));
  178. Add.Margin = new Thickness(0, 2, 2, 0);
  179. Add.Click += Add_Click;
  180. Edit = CreateButton(Wpf.Resources.pencil.AsBitmapImage(Color.White));
  181. Edit.Margin = new Thickness(0, 2, 2, 0);
  182. Edit.Click += Edit_Click;
  183. SwitchViewBtn = CreateButton(Wpf.Resources.alter.AsBitmapImage());
  184. SwitchViewBtn.Margin = new Thickness(0, 2, 2, 0);
  185. SwitchViewBtn.Click += SwitchView_Click;
  186. EditSpacer = new Label { Width = 5 };
  187. Print = CreateButton(Wpf.Resources.print.AsBitmapImage(Color.White));
  188. Print.Margin = new Thickness(0, 2, 2, 0);
  189. Print.Click += (o, e) => DoPrint(o);
  190. PrintSpacer = new Label { Width = 5 };
  191. Cut = CreateButton(Wpf.Resources.cut.AsBitmapImage(Color.White));
  192. Cut.Margin = new Thickness(0, 2, 2, 0);
  193. Cut.Click += Cut_Click;
  194. Copy = CreateButton(Wpf.Resources.copy.AsBitmapImage(Color.White));
  195. Copy.Margin = new Thickness(0, 2, 2, 0);
  196. Copy.Click += Copy_Click;
  197. Paste = CreateButton(Wpf.Resources.paste.AsBitmapImage(Color.White));
  198. Paste.Margin = new Thickness(0, 2, 2, 0);
  199. Paste.Click += Paste_Click;
  200. ClipboardSpacer = new Label { Width = 5 };
  201. Export = CreateButton(Wpf.Resources.doc_xls.AsBitmapImage(Color.White), "Export");
  202. Export.Margin = new Thickness(0, 2, 2, 0);
  203. Export.Click += Export_Click;
  204. Import = CreateButton(Wpf.Resources.doc_xls.AsBitmapImage(Color.White), "Import");
  205. Import.Margin = new Thickness(0, 2, 2, 0);
  206. Import.Click += Import_Click;
  207. ExportSpacer = new Label { Width = 5 };
  208. LeftButtonStack = new StackPanel();
  209. LeftButtonStack.Orientation = Orientation.Horizontal;
  210. LeftButtonStack.SetValue(DockPanel.DockProperty, Dock.Left);
  211. LeftButtonStack.Children.Add(Help);
  212. LeftButtonStack.Children.Add(Add);
  213. LeftButtonStack.Children.Add(Edit);
  214. LeftButtonStack.Children.Add(SwitchViewBtn);
  215. //Stack.Children.Add(MultiEdit);
  216. LeftButtonStack.Children.Add(EditSpacer);
  217. LeftButtonStack.Children.Add(Print);
  218. LeftButtonStack.Children.Add(PrintSpacer);
  219. LeftButtonStack.Children.Add(Cut);
  220. LeftButtonStack.Children.Add(Copy);
  221. LeftButtonStack.Children.Add(Paste);
  222. LeftButtonStack.Children.Add(ClipboardSpacer);
  223. LeftButtonStack.Children.Add(Export);
  224. LeftButtonStack.Children.Add(Import);
  225. LeftButtonStack.Children.Add(ExportSpacer);
  226. RightButtonStack = new StackPanel();
  227. RightButtonStack.Orientation = Orientation.Horizontal;
  228. RightButtonStack.SetValue(DockPanel.DockProperty, Dock.Right);
  229. Delete = CreateButton(Wpf.Resources.delete.AsBitmapImage(Color.White));
  230. Delete.Margin = new Thickness(2, 2, 0, 0);
  231. Delete.SetValue(DockPanel.DockProperty, Dock.Right);
  232. Delete.Click += Delete_Click;
  233. DuplicateBtn = AddButton("Duplicate", Wpf.Resources.paste.AsBitmapImage(Color.White), DoDuplicate);
  234. Count = new Label();
  235. Count.Height = 30;
  236. Count.Margin = new Thickness(0, 2, 0, 0);
  237. Count.VerticalContentAlignment = VerticalAlignment.Center;
  238. Count.HorizontalContentAlignment = HorizontalAlignment.Center;
  239. Count.SetValue(DockPanel.DockProperty, Dock.Left);
  240. Docker = new DockPanel();
  241. Docker.SetValue(Grid.RowProperty, 2);
  242. Docker.SetValue(Grid.ColumnProperty, 0);
  243. Docker.Children.Add(LeftButtonStack);
  244. Docker.Children.Add(Delete);
  245. Docker.Children.Add(RightButtonStack);
  246. Docker.Children.Add(Count);
  247. Layout = new Grid();
  248. Layout.ColumnDefinitions.Add(new ColumnDefinition { Width = new GridLength(1, GridUnitType.Star) });
  249. Layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  250. Layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Star) });
  251. Layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  252. var control = UIComponent.Control;
  253. control.SetValue(Grid.RowProperty, 1);
  254. Layout.Children.Add(control);
  255. Layout.Children.Add(Loading);
  256. Layout.Children.Add(Docker);
  257. Disabler = new Border()
  258. {
  259. BorderBrush = new SolidColorBrush(Colors.Transparent),
  260. Background = new SolidColorBrush(Colors.DimGray) { Opacity = 0.2 },
  261. Visibility = Visibility.Collapsed,
  262. };
  263. Disabler.SetValue(Canvas.ZIndexProperty, 99);
  264. Disabler.SetValue(Grid.RowSpanProperty, 3);
  265. Layout.Children.Add(Disabler);
  266. //Scroll.ApplyTemplate();
  267. Content = Layout;
  268. IsEnabledChanged += (sender, args) =>
  269. {
  270. Disabler.Visibility = Equals(args.NewValue, true)
  271. ? Visibility.Collapsed
  272. : Visibility.Visible;
  273. };
  274. Settings = LoadSettings();
  275. Init();
  276. Reconfigure();
  277. }
  278. #region IDynamicGridUIComponentParent
  279. protected virtual IDynamicGridUIComponent<T> CreateUIComponent()
  280. {
  281. return new DynamicGridGridUIComponent<T>()
  282. {
  283. Parent = this
  284. };
  285. }
  286. bool IDynamicGridUIComponentParent<T>.CanSort()
  287. {
  288. return !ShowSequenceButtons || !Options.EditRows;
  289. }
  290. T IDynamicGrid<T>.LoadItem(CoreRow row) => LoadItem(row);
  291. DynamicGridRowStyleSelector<T> IDynamicGridUIComponentParent<T>.RowStyleSelector => RowStyleSelector;
  292. void IDynamicGridUIComponentParent<T>.BeforeSelection(CancelEventArgs cancel)
  293. {
  294. BeforeSelection(cancel);
  295. }
  296. void IDynamicGridUIComponentParent<T>.SelectItems(CoreRow[] rows)
  297. {
  298. SelectItems(rows);
  299. }
  300. void IDynamicGridUIComponentParent<T>.EntityChanged(T obj, CoreRow row, string changedColumn, Dictionary<string, object?> changes)
  301. => EntityChanged(obj, row, changedColumn, changes);
  302. void IDynamicGridUIComponentParent<T>.UpdateData(T obj, CoreRow row, string changedColumn, Dictionary<CoreColumn, object?> updates)
  303. {
  304. var result = new Dictionary<string, object?>();
  305. foreach (var (col, value) in updates)
  306. {
  307. UpdateRow(row, col.ColumnName, value, refresh: false);
  308. DynamicGridUtils.UpdateEditorValue(new BaseObject[] { obj }, col.ColumnName, value, result);
  309. }
  310. EntityChanged(obj, row, changedColumn, result);
  311. }
  312. void IDynamicGridUIComponentParent<T>.HandleKey(KeyEventArgs e)
  313. {
  314. if (ShowSequenceButtons)
  315. {
  316. if (e.Key == Key.X && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  317. {
  318. CutToClipBuffer();
  319. }
  320. else if (e.Key == Key.C && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  321. {
  322. CopyToClipBuffer();
  323. }
  324. else if (e.Key == Key.V && (Keyboard.Modifiers & ModifierKeys.Control) == ModifierKeys.Control)
  325. {
  326. PasteFromClipBuffer();
  327. }
  328. else if (e.Key == Key.Escape)
  329. {
  330. ResetClipBuffer();
  331. InvalidateGrid();
  332. }
  333. }
  334. }
  335. void IDynamicGridUIComponentParent<T>.DoubleClickCell(CoreRow? row, DynamicColumnBase? column)
  336. {
  337. var args = new DynamicGridCellClickEventArgs(row, column);
  338. if (OnCellDoubleClick is not null && column is DynamicGridColumn col)
  339. {
  340. OnCellDoubleClick?.Invoke(this, args);
  341. if (args.Handled)
  342. return;
  343. }
  344. if (row is not null)
  345. DoDoubleClick(this, args);
  346. }
  347. void IDynamicGridUIComponentParent<T>.ExecuteActionColumn(DynamicActionColumn column, CoreRow[]? rows)
  348. {
  349. var bRefresh = false;
  350. if(rows is null)
  351. {
  352. bRefresh = column.Action?.Invoke(null) ?? false;
  353. }
  354. else
  355. {
  356. foreach (var row in rows)
  357. if (column.Action?.Invoke(row) == true)
  358. bRefresh = true;
  359. }
  360. if (bRefresh)
  361. Dispatcher.BeginInvoke(() => { Refresh(true, true); });
  362. }
  363. void IDynamicGridUIComponentParent<T>.OpenColumnMenu(DynamicColumnBase column)
  364. {
  365. if(column is DynamicMenuColumn menuColumn)
  366. {
  367. menuColumn.Action?.Invoke(SelectedRows.FirstOrDefault());
  368. }
  369. else if(column is DynamicActionColumn actionColumn)
  370. {
  371. var menu = actionColumn?.ContextMenu?.Invoke(SelectedRows);
  372. if (menu != null && menu.Items.Count > 0)
  373. {
  374. menu.IsOpen = true;
  375. }
  376. }
  377. }
  378. void IDynamicGridUIComponentParent<T>.UpdateRecordCount(int count)
  379. {
  380. Count.Content = string.Format("{0} Records", count);
  381. }
  382. void IDynamicGridUIComponentParent<T>.LoadColumnsMenu(ContextMenu menu)
  383. {
  384. menu.AddItem("Select Columns", null, SelectColumnsClick);
  385. LoadColumnsMenu(menu);
  386. }
  387. void IDynamicGridUIComponentParent<T>.DragOver(object sender, DragEventArgs e)
  388. {
  389. HandleDragOver(sender, e);
  390. }
  391. void IDynamicGridUIComponentParent<T>.Drop(object sender, DragEventArgs e)
  392. {
  393. if (!Options.DragTarget)
  394. return;
  395. if(DynamicGridUtils.TryGetDropData(e, out var entityType, out var table))
  396. {
  397. OnDragEnd(entityType, table, e);
  398. }
  399. else
  400. {
  401. HandleDragDrop(sender, e);
  402. }
  403. }
  404. void IDynamicGridUIComponentParent<T>.DragStart(object? sender, CoreRow[] rows)
  405. {
  406. Logger.Send(LogType.Information, "", "RowDragDropController_DragStart");
  407. if (!Options.DragSource)
  408. return;
  409. OnRowsDragStart(rows);
  410. }
  411. void IDynamicGridUIComponentParent<T>.UIFilterChanged(object sender) => DoFilterChanged();
  412. protected virtual void DoFilterChanged()
  413. {
  414. }
  415. IEnumerable<string>? IDynamicGridUIComponentParent<T>.GetColumnFilterItems(DynamicColumnBase column) => GetColumnFilterItems(column);
  416. protected virtual IEnumerable<string>? GetColumnFilterItems(DynamicColumnBase column)
  417. {
  418. return null;
  419. }
  420. #endregion
  421. protected virtual DynamicGridRowStyleSelector<T> GetRowStyleSelector()
  422. {
  423. return new DynamicGridRowStyleSelector<T, DynamicGridRowStyle>();
  424. }
  425. protected virtual DynamicGridStyle GetRowStyle(CoreRow row, DynamicGridStyle style)
  426. {
  427. DynamicGridStyle? result = null;
  428. if (ClipBuffer != null)
  429. if (ClipBuffer.Item2.Contains(row))
  430. {
  431. var bgbrush = style.Background as SolidColorBrush;
  432. var bgcolor = bgbrush != null ? bgbrush.Color : Colors.Transparent;
  433. result = new DynamicGridRowStyle(style);
  434. result.Background = ClipBuffer.Item1 == ClipAction.Cut
  435. ? new SolidColorBrush(bgcolor.MixColors(0.5, Colors.Orchid))
  436. : new SolidColorBrush(bgcolor.MixColors(0.5, Colors.LightGreen));
  437. result.Foreground = new SolidColorBrush(Colors.Gray);
  438. result.FontStyle = FontStyles.Italic;
  439. }
  440. result ??= OnGetRowStyle != null ? OnGetRowStyle(row, style) : style;
  441. return result;
  442. }
  443. protected virtual void BeforeSelection(CancelEventArgs cancel)
  444. {
  445. OnBeforeSelection?.Invoke(cancel);
  446. }
  447. public bool IsReady { get; protected set; }
  448. public UIElement? Header
  449. {
  450. get => _header;
  451. set
  452. {
  453. if (_header is not null && Layout.Children.Contains(_header))
  454. Layout.Children.Remove(_header);
  455. _header = value;
  456. if (_header is not null)
  457. {
  458. _header.SetValue(Grid.RowProperty, 0);
  459. _header.SetValue(Grid.ColumnProperty, 0);
  460. _header.SetValue(Grid.ColumnSpanProperty, 2);
  461. Layout.Children.Add(_header);
  462. }
  463. }
  464. }
  465. /// <summary>
  466. /// Represents the data in the grid. This is <see langword="null"/> until <see cref="Refresh(bool, bool)"/> is called.
  467. /// </summary>
  468. public CoreTable? MasterData { get; set; }
  469. public DynamicGridColumns MasterColumns { get; protected set; }
  470. public DynamicGridColumns VisibleColumns { get; protected set; }
  471. public DynamicActionColumns ActionColumns { get; protected set; }
  472. public CoreTable Data { get; set; }
  473. public class HiddenColumnsList
  474. {
  475. private List<string> Columns { get; set; } = new();
  476. public IEnumerable<string> ColumnNames => Columns;
  477. public void Add(Expression<Func<T, object?>> column) => Add(CoreUtils.GetFullPropertyName(column, "."));
  478. public void Add(IColumn column) => Add(column.Property);
  479. public void Add(string column)
  480. {
  481. if (!Contains(column))
  482. Columns.Add(column);
  483. }
  484. public bool Contains(string column) => Columns.Contains(column);
  485. }
  486. public void AddHiddenColumn(string column) => HiddenColumns.Add(column);
  487. public HiddenColumnsList HiddenColumns { get; }
  488. private static bool IsSequenced => typeof(T).GetInterfaces().Any(x => x.Equals(typeof(ISequenceable)));
  489. protected virtual bool ShowSequenceButtons => IsSequenced;
  490. public double RowHeight
  491. {
  492. get => UIComponent.RowHeight;
  493. set => UIComponent.RowHeight = value;
  494. }
  495. public double HeaderHeight
  496. {
  497. get => UIComponent.HeaderRowHeight;
  498. set => UIComponent.HeaderRowHeight = value;
  499. }
  500. #region Options
  501. /// <summary>
  502. /// Initialise things like custom buttons; called once during construction.
  503. /// </summary>
  504. protected abstract void Init();
  505. protected abstract void DoReconfigure(DynamicGridOptions options);
  506. private bool _hasLoadedOptions = false;
  507. protected virtual void OptionsChanged()
  508. {
  509. var reloadColumns = false;
  510. Help.Visibility = Options.ShowHelp ? Visibility.Visible : Visibility.Collapsed;
  511. Add.Visibility = Options.AddRows ? Visibility.Visible : Visibility.Collapsed;
  512. Edit.Visibility = Options.EditRows ? Visibility.Visible : Visibility.Collapsed;
  513. EditSpacer.Visibility = Options.AddRows || Options.EditRows
  514. ? Visibility.Visible
  515. : Visibility.Collapsed;
  516. Print.Visibility = Options.Print ? Visibility.Visible : Visibility.Collapsed;
  517. PrintSpacer.Visibility = Options.Print ? Visibility.Visible : Visibility.Collapsed;
  518. Cut.Visibility = ShowSequenceButtons && Options.EditRows ? Visibility.Visible : Visibility.Collapsed;
  519. Copy.Visibility = ShowSequenceButtons && Options.EditRows ? Visibility.Visible : Visibility.Collapsed;
  520. Paste.Visibility = ShowSequenceButtons && Options.EditRows ? Visibility.Visible : Visibility.Collapsed;
  521. ClipboardSpacer.Visibility = ShowSequenceButtons && Options.EditRows ? Visibility.Visible : Visibility.Collapsed;
  522. Export.Visibility = Options.ExportData ? Visibility.Visible : Visibility.Collapsed;
  523. Import.Visibility = Options.ImportData ? Visibility.Visible : Visibility.Collapsed;
  524. ExportSpacer.Visibility = Options.ExportData || Options.ImportData
  525. ? Visibility.Visible
  526. : Visibility.Collapsed;
  527. SwitchViewBtn.Visibility = Options.DirectEdit
  528. ? Options.HideDirectEditButton
  529. ? Visibility.Collapsed
  530. : Visibility.Visible
  531. : Visibility.Collapsed;
  532. Count.Visibility = Options.RecordCount ? Visibility.Visible : Visibility.Collapsed;
  533. Delete.Visibility = Options.DeleteRows ? Visibility.Visible : Visibility.Collapsed;
  534. if (up != null && down != null)
  535. {
  536. var hasSequence = up.Position == DynamicActionColumnPosition.Start;
  537. var shouldHaveSequence = Options.EditRows;
  538. if(hasSequence != shouldHaveSequence)
  539. {
  540. up.Position = Options.EditRows ? DynamicActionColumnPosition.Start : DynamicActionColumnPosition.Hidden;
  541. down.Position = Options.EditRows ? DynamicActionColumnPosition.Start : DynamicActionColumnPosition.Hidden;
  542. reloadColumns = true;
  543. }
  544. }
  545. if (DuplicateBtn != null)
  546. DuplicateBtn.Visibility = Visibility.Collapsed;
  547. reloadColumns = reloadColumns || UIComponent.OptionsChanged();
  548. if(reloadColumns && IsReady)
  549. {
  550. Refresh(true, false);
  551. }
  552. }
  553. public bool IsDirectEditMode()
  554. {
  555. return Options.DirectEdit
  556. && (Settings.ViewMode == DynamicGridSettings.DynamicGridViewMode.DirectEdit
  557. || Settings.ViewMode == DynamicGridSettings.DynamicGridViewMode.Default);
  558. }
  559. private void SwitchView_Click(object sender, RoutedEventArgs e)
  560. {
  561. Settings.ViewMode = Settings.ViewMode switch
  562. {
  563. DynamicGridSettings.DynamicGridViewMode.Default => DynamicGridSettings.DynamicGridViewMode.Normal,
  564. DynamicGridSettings.DynamicGridViewMode.Normal => DynamicGridSettings.DynamicGridViewMode.DirectEdit,
  565. DynamicGridSettings.DynamicGridViewMode.DirectEdit or _ => DynamicGridSettings.DynamicGridViewMode.Normal
  566. };
  567. SaveSettings(Settings);
  568. Reconfigure();
  569. }
  570. public DynamicGridOptions Options { get; }
  571. protected void OnReconfigureEvent(DynamicGridOptions options)
  572. {
  573. OnReconfigure?.Invoke(options);
  574. }
  575. /// <summary>
  576. /// Configure custom buttons and options.
  577. /// </summary>
  578. public void Reconfigure(DynamicGridOptions options)
  579. {
  580. options.BeginUpdate().Clear();
  581. DoReconfigure(options);
  582. OnReconfigureEvent(options);
  583. options.EndUpdate();
  584. if (!_hasLoadedOptions)
  585. {
  586. _hasLoadedOptions = true;
  587. OptionsChanged();
  588. }
  589. }
  590. public void Reconfigure()
  591. {
  592. Reconfigure(Options);
  593. }
  594. public void Reconfigure(ReconfigureEvent onReconfigure)
  595. {
  596. OnReconfigure += onReconfigure;
  597. Reconfigure();
  598. }
  599. #endregion
  600. protected virtual DynamicGridSettings LoadSettings()
  601. {
  602. return new DynamicGridSettings();
  603. }
  604. protected virtual void SaveSettings(DynamicGridSettings settings)
  605. {
  606. }
  607. protected virtual void LoadColumnsMenu(ContextMenu menu)
  608. {
  609. }
  610. protected void UpdateCell(int row, string colname, object? value)
  611. {
  612. var coreRow = Data.Rows[row];
  613. coreRow[colname] = value;
  614. UIComponent.UpdateCell(coreRow, colname, value);
  615. }
  616. private void EntityChanged(T obj, CoreRow row, string changedColumn, Dictionary<string, object?> changes)
  617. {
  618. OnAfterEditorValueChanged(null, [obj], new AfterEditorValueChangedArgs(changedColumn, changes), changes);
  619. SaveItem(obj);
  620. foreach (var (key, value) in changes)
  621. {
  622. row[key] = value;
  623. }
  624. UIComponent.UpdateRow(row);
  625. }
  626. #region Row Selections
  627. protected CoreRow[] GetVisibleRows()
  628. {
  629. return UIComponent.GetVisibleRows();
  630. }
  631. public CoreRow[] SelectedRows
  632. {
  633. get => UIComponent.SelectedRows;
  634. set => UIComponent.SelectedRows = value;
  635. }
  636. /// <summary>
  637. /// Call the <see cref="OnSelectItem"/> event, and do any updating which needs to occur when items are selected.
  638. /// </summary>
  639. /// <param name="rows"></param>
  640. protected virtual void SelectItems(CoreRow[]? rows)
  641. {
  642. if (IsReady)
  643. OnSelectItem?.Invoke(this, new DynamicGridSelectionEventArgs(rows));
  644. DuplicateBtn.Visibility =
  645. typeof(T).IsAssignableTo(typeof(IDuplicatable)) && rows != null && rows.Length >= 1 ? Visibility.Visible : Visibility.Collapsed;
  646. }
  647. protected virtual void DoDoubleClick(object sender, DynamicGridCellClickEventArgs args)
  648. {
  649. if (IsDirectEditMode())
  650. return;
  651. //SelectItems(SelectedRows);
  652. var e = new HandledEventArgs(false);
  653. OnDoubleClick?.Invoke(sender, e);
  654. if (e.Handled)
  655. return;
  656. if (Options.EditRows)
  657. DoEdit();
  658. }
  659. #endregion
  660. #region Column Handling
  661. #region Column Grouping
  662. public DynamicGridColumnGroupings ColumnGroupings { get; set; }
  663. /// <summary>
  664. /// Create a new column header group, and return it for editing.
  665. /// </summary>
  666. /// <returns></returns>
  667. public DynamicGridColumnGrouping AddColumnGrouping()
  668. {
  669. var group = new DynamicGridColumnGrouping();
  670. ColumnGroupings.Add(group);
  671. return group;
  672. }
  673. /// <summary>
  674. /// Gets the current column header group, and if there is none, create a new one.
  675. /// </summary>
  676. /// <returns></returns>
  677. public DynamicGridColumnGrouping GetColumnGrouping()
  678. {
  679. if(ColumnGroupings.Count == 0)
  680. {
  681. return AddColumnGrouping();
  682. }
  683. return ColumnGroupings[^1];
  684. }
  685. #endregion
  686. protected virtual DynamicGridColumns LoadColumns()
  687. {
  688. return GenerateColumns();
  689. }
  690. /// <summary>
  691. /// Provide a set of columns which is the default for this grid.
  692. /// </summary>
  693. public virtual DynamicGridColumns GenerateColumns()
  694. {
  695. var columns = new DynamicGridColumns();
  696. var cols = IsDirectEditMode()
  697. ? new Columns<T>(ColumnTypeFlags.IncludeVisible | ColumnTypeFlags.IncludeForeignKeys)
  698. : new Columns<T>(ColumnTypeFlags.IncludeVisible | ColumnTypeFlags.IncludeLinked);
  699. foreach (var col in cols)
  700. {
  701. var mc = MasterColumns.FirstOrDefault(x => x.ColumnName.Equals(col.Property));
  702. if (mc != null && mc.Editor is not NullEditor && mc.Editor.Visible != Visible.Hidden)
  703. columns.Add(mc);
  704. }
  705. return columns;
  706. }
  707. private bool SwapRows(int row1, int row2)
  708. {
  709. CoreRow[] rows = Data.Rows.Where(x => x.Index.Equals(row1) || x.Index.Equals(row2)).ToArray();
  710. var items = LoadItems(rows);
  711. var first = (items.First() as ISequenceable)!;
  712. var last = (items.Last() as ISequenceable)!;
  713. var iBuf1 = first.Sequence;
  714. var iBuf2 = last.Sequence;
  715. first.Sequence = iBuf2;
  716. last.Sequence = iBuf1;
  717. SaveItems(items);
  718. return true;
  719. }
  720. protected virtual void SaveColumns(DynamicGridColumns columns)
  721. {
  722. }
  723. public int DesiredWidth()
  724. {
  725. return UIComponent.DesiredWidth();
  726. }
  727. /// <summary>
  728. /// Handle to configure column groups.
  729. /// </summary>
  730. /// <remarks>
  731. /// This is called after <see cref="LoadColumns"/>, so by the time this is called, both <see cref="VisibleColumns"/>
  732. /// and <see cref="ActionColumns"/> will be loaded, which means one can reference these in the column groups.
  733. /// <br/>
  734. /// <b>Note:</b> <see cref="ColumnGroupings"/> is cleared before this function is called.
  735. /// </remarks>
  736. protected virtual void ConfigureColumnGroups()
  737. {
  738. }
  739. private void ReloadColumns()
  740. {
  741. VisibleColumns = LoadColumns();
  742. ColumnGroupings.Clear();
  743. ConfigureColumnGroups();
  744. UIComponent.RefreshColumns(VisibleColumns, ActionColumns, ColumnGroupings);
  745. }
  746. #endregion
  747. #region Refresh / Reload
  748. protected abstract void Reload(Filters<T> criteria, Columns<T> columns, ref SortOrder<T>? sort, Action<CoreTable?, Exception?> action);
  749. public Filter<T>? DefineFilter()
  750. {
  751. if (OnDefineFilter is null)
  752. return null;
  753. var result = OnDefineFilter.Invoke(typeof(T)) as Filter<T>;
  754. return result;
  755. }
  756. protected virtual bool FilterRecord(CoreRow row)
  757. {
  758. var bOK = ActionColumns.All(x =>
  759. {
  760. return x.FilterRecord is null
  761. || ((x.SelectedFilters is null || x.SelectedFilters.Length == 0 || x.FilterRecord.Invoke(row, x.SelectedFilters))
  762. && (x.ExcludeFilters is null || x.ExcludeFilters.Length == 0 || !x.FilterRecord.Invoke(row, x.ExcludeFilters)));
  763. });
  764. if (bOK && OnFilterRecord is not null)
  765. bOK = OnFilterRecord(row);
  766. return bOK;
  767. }
  768. public IEnumerable<TType> ExtractValues<TType>(Expression<Func<T, TType>> column, Selection selection)
  769. {
  770. var result = selection == Selection.None
  771. ? Enumerable.Empty<TType>()
  772. : selection == Selection.Selected
  773. ? SelectedRows.Select(r => r.Get(column))
  774. : Data.ExtractValues(column);
  775. return result;
  776. }
  777. public virtual void Refresh(bool reloadcolumns, bool reloaddata)
  778. {
  779. if (bRefreshing)
  780. return;
  781. if (!DoBeforeRefresh())
  782. return;
  783. UIComponent.BeforeRefresh();
  784. var cursor = UseWaitCursor ? new WaitCursor() : null;
  785. Loading.Visibility = Visibility.Visible;
  786. Loading.BeginAnimation(Label.OpacityProperty, LoadingFader);
  787. bRefreshing = true;
  788. if (reloadcolumns)
  789. ReloadColumns();
  790. if (reloaddata)
  791. {
  792. _lookupcache.Clear();
  793. var criteria = new Filters<T>();
  794. var filter = DefineFilter();
  795. if (filter != null)
  796. criteria.Add(filter);
  797. var columns = DataColumns();
  798. var sort = LookupFactory.DefineSort<T>();
  799. if (sort == null && IsSequenced)
  800. sort = new SortOrder<T>("Sequence");
  801. Reload(
  802. criteria
  803. , columns
  804. , ref sort
  805. , (table, exception) =>
  806. {
  807. if (exception != null)
  808. {
  809. Dispatcher.Invoke(() =>
  810. {
  811. MessageWindow.ShowError("Sorry! We couldn't load the data.", exception);
  812. });
  813. }
  814. else if (table is not null)
  815. {
  816. MasterData = table;
  817. Dispatcher.Invoke(() =>
  818. {
  819. ProcessData();
  820. DoAfterRefresh();
  821. bRefreshing = false;
  822. IsReady = true;
  823. });
  824. }
  825. }
  826. );
  827. }
  828. else
  829. {
  830. ProcessData();
  831. DoAfterRefresh();
  832. bRefreshing = false;
  833. IsReady = true;
  834. Loading.BeginAnimation(Label.OpacityProperty, null);
  835. Loading.Visibility = Visibility.Collapsed;
  836. }
  837. if (cursor != null)
  838. {
  839. cursor.Dispose();
  840. cursor = null;
  841. }
  842. }
  843. protected void NotifyBeforeRefresh(BeforeRefreshEventArgs args) => BeforeRefresh?.Invoke(this, args);
  844. protected void NotifyAfterRefresh(AfterRefreshEventArgs args) => AfterRefresh?.Invoke(this, args);
  845. protected bool OnBeforeRefresh()
  846. {
  847. return true;
  848. }
  849. private bool DoBeforeRefresh()
  850. {
  851. var result = OnBeforeRefresh();
  852. if (result)
  853. {
  854. var args = new BeforeRefreshEventArgs() { Cancel = false };
  855. NotifyBeforeRefresh(args);
  856. result = args.Cancel == false;
  857. }
  858. return result;
  859. }
  860. protected virtual void OnAfterRefresh()
  861. {
  862. }
  863. protected void DoAfterRefresh()
  864. {
  865. OnAfterRefresh();
  866. NotifyAfterRefresh(new AfterRefreshEventArgs());
  867. }
  868. public Columns<T> DataColumns()
  869. {
  870. var columns = Columns.None<T>();
  871. foreach (var column in VisibleColumns)
  872. columns.Add(column.ColumnName);
  873. foreach (var column in HiddenColumns.ColumnNames)
  874. columns.Add(new Column<T>(column));
  875. return columns;
  876. }
  877. private void ProcessData()
  878. {
  879. Data.Columns.Clear();
  880. Data.Setters.Clear();
  881. if (MasterData != null)
  882. foreach (var column in MasterData.Columns)
  883. Data.Columns.Add(column);
  884. LoadData();
  885. }
  886. protected readonly Dictionary<CoreRow, CoreRow> _recordmap = new();
  887. public void UpdateRow<TRow, TType>(CoreRow row, Expression<Func<TRow, TType>> column, TType value, bool refresh = true)
  888. {
  889. row.Set(column, value);
  890. _recordmap[row].Set(column, value);
  891. if (refresh)
  892. InvalidateRow(row);
  893. }
  894. public void UpdateRow<TType>(CoreRow row, string column, TType value, bool refresh = true)
  895. {
  896. row.Set(column, value);
  897. _recordmap[row].Set(column, value);
  898. if (refresh)
  899. InvalidateRow(row);
  900. }
  901. public void UpdateRow(CoreRow row, T obj)
  902. {
  903. ObjectToRow(obj, row);
  904. ObjectToRow(obj, _recordmap[row]);
  905. }
  906. public void AddRow(CoreRow row)
  907. {
  908. if (MasterData is null) return;
  909. var masterrow = MasterData.NewRow();
  910. MasterData.FillRow(masterrow, row);
  911. Refresh(false, false);
  912. }
  913. public void AddRow(T data)
  914. {
  915. if (MasterData is null) return;
  916. MasterData.LoadRow(data);
  917. Refresh(false, false);
  918. }
  919. public void DeleteRow(CoreRow row)
  920. {
  921. if (MasterData is null) return;
  922. var masterrow = _recordmap[row];
  923. MasterData.Rows.Remove(masterrow);
  924. Refresh(false, false);
  925. }
  926. private void FilterRows(CoreTable from, CoreTable into, Dictionary<CoreRow, CoreRow>? recordMap = null, Func<CoreRow, bool>? filter = null)
  927. {
  928. into.Rows.Clear();
  929. recordMap?.Clear();
  930. foreach (var row in from.Rows.ToArray())
  931. if (FilterRecord(row) && filter?.Invoke(row) != false)
  932. {
  933. var newrow = into.NewRow();
  934. for (var i = 0; i < into.Columns.Count; i++)
  935. {
  936. var value = i < row.Values.Count ? row.Values[i] : null;
  937. if (into.Columns[i].DataType.IsNumeric())
  938. value = into.Columns[i].DataType.IsDefault(value) ? null : value;
  939. //else if (Data.Columns[i].DataType == typeof(String[]))
  940. // value = String.Join("\n", value as String[]);
  941. newrow.Values.Add(value);
  942. }
  943. //newrow.Values.AddRange(row.Values);
  944. //if ((OnFilterRecord == null) || (OnFilterRecord(row)))
  945. into.Rows.Add(newrow);
  946. recordMap?.TryAdd(newrow, row);
  947. }
  948. }
  949. private void LoadData()
  950. {
  951. ResetClipBuffer();
  952. if (MasterData is null)
  953. return;
  954. FilterRows(MasterData, Data, _recordmap);
  955. InvalidateGrid();
  956. //ScrollBar.Value = _CurrentRow <= 0 ? 0 : _CurrentRow;
  957. SelectedRows = Array.Empty<CoreRow>();
  958. }
  959. //IncrementalList<T> _data = null;
  960. public void InvalidateRow(CoreRow row)
  961. {
  962. UIComponent.InvalidateRow(row);
  963. }
  964. protected void InvalidateGrid()
  965. {
  966. if (RowStyleSelector != null)
  967. RowStyleSelector.Data = Data;
  968. UIComponent.RefreshData(Data);
  969. Loading.BeginAnimation(Label.OpacityProperty, null);
  970. Loading.Visibility = Visibility.Collapsed;
  971. }
  972. public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  973. {
  974. UIComponent.AddVisualFilter(column, value, filtertype);
  975. }
  976. protected List<Tuple<string, Func<CoreRow, bool>>> GetFilterPredicates()
  977. {
  978. return UIComponent.GetFilterPredicates();
  979. }
  980. #endregion
  981. #region Item Manipulation
  982. #region Load/Save/Delete
  983. public virtual T[] LoadItems(CoreRow[] rows)
  984. {
  985. var result = new List<T>();
  986. foreach (var row in rows)
  987. {
  988. var index = Data.Rows.IndexOf(row);
  989. result.Add(LoadItem(row));
  990. }
  991. return result.ToArray();
  992. }
  993. public abstract T LoadItem(CoreRow row);
  994. public abstract void SaveItem(T item);
  995. public virtual void SaveItems(T[] items)
  996. {
  997. foreach (var item in items)
  998. SaveItem(item);
  999. }
  1000. protected virtual bool CanDeleteItems(params CoreRow[] rows)
  1001. {
  1002. return true;
  1003. }
  1004. public abstract void DeleteItems(params CoreRow[] rows);
  1005. protected virtual void DoDelete()
  1006. {
  1007. var rows = SelectedRows.ToArray();
  1008. if (rows.Any())
  1009. if (CanDeleteItems(rows))
  1010. if (MessageBox.Show("Are you sure you wish to delete the selected records?", "Confirm Delete", MessageBoxButton.YesNo) ==
  1011. MessageBoxResult.Yes)
  1012. {
  1013. DeleteItems(rows);
  1014. SelectedRows = Array.Empty<CoreRow>();
  1015. OnChanged?.Invoke(this, EventArgs.Empty);
  1016. Refresh(false, true);
  1017. SelectItems(null);
  1018. }
  1019. }
  1020. private void Delete_Click(object sender, RoutedEventArgs e)
  1021. {
  1022. DoDelete();
  1023. }
  1024. #endregion
  1025. #region Edit
  1026. protected virtual void DoEdit()
  1027. {
  1028. if (SelectedRows.Length == 0)
  1029. return;
  1030. if (AddEditClick(SelectedRows))
  1031. {
  1032. SelectItems(SelectedRows);
  1033. }
  1034. }
  1035. private void Edit_Click(object sender, RoutedEventArgs e)
  1036. {
  1037. DoEdit();
  1038. }
  1039. protected virtual void DoAdd(bool OpenEditorOnDirectEdit = false)
  1040. {
  1041. //CoreRow row = (SelectedRow > -1) && (SelectedRow < Data.Rows.Count) ? Data.Rows[this.SelectedRow] : null;
  1042. if (IsDirectEditMode() && !OpenEditorOnDirectEdit)
  1043. {
  1044. CreateItems(null);
  1045. }
  1046. else if (AddEditClick(null))
  1047. {
  1048. Refresh(false, true);
  1049. }
  1050. }
  1051. protected void CreateItems(Func<IEnumerable<T>>? create)
  1052. {
  1053. var newRows = new List<CoreRow>();
  1054. var items = create?.Invoke() ?? CoreUtils.One(CreateItem());
  1055. foreach (var item in items)
  1056. {
  1057. if (!AfterCreate(item))
  1058. return;
  1059. SaveItem(item);
  1060. var datarow = Data.NewRow();
  1061. ObjectToRow(item, datarow);
  1062. Data.Rows.Add(datarow);
  1063. newRows.Add(datarow);
  1064. var masterrow = MasterData.NewRow();
  1065. ObjectToRow(item, masterrow);
  1066. MasterData.Rows.Add(masterrow);
  1067. _recordmap[datarow] = masterrow;
  1068. }
  1069. InvalidateGrid();
  1070. SelectedRows = newRows.ToArray();
  1071. OnChanged?.Invoke(this, EventArgs.Empty);
  1072. }
  1073. private void Add_Click(object sender, RoutedEventArgs e)
  1074. {
  1075. if (CanCreateItems())
  1076. DoAdd();
  1077. }
  1078. public virtual DynamicEditorPages LoadEditorPages(T item)
  1079. {
  1080. DynamicEditorPages pages = new DynamicEditorPages();
  1081. DynamicGridUtils.LoadOneToManyPages(typeof(T), pages);
  1082. DynamicGridUtils.LoadEnclosedListPages(typeof(T), pages);
  1083. DynamicGridUtils.LoadManyToManyPages(typeof(T), pages);
  1084. DynamicGridUtils.LoadCustomEditorPages(typeof(T), pages);
  1085. foreach (var page in pages)
  1086. page.Ready = false;
  1087. return pages;
  1088. }
  1089. public virtual void LoadEditorButtons(T item, DynamicEditorButtons buttons)
  1090. {
  1091. buttons.Clear();
  1092. buttons.Add(
  1093. "",
  1094. Wpf.Resources.help.AsBitmapImage(),
  1095. item,
  1096. (f, i) =>
  1097. {
  1098. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + typeof(T).Name.SplitCamelCase().Replace(" ", "_"))
  1099. { UseShellExecute = true });
  1100. }
  1101. );
  1102. OnLoadEditorButtons?.Invoke(item, buttons);
  1103. }
  1104. protected virtual void BeforeLoad(IDynamicEditorForm form, T[] items)
  1105. {
  1106. form.BeforeLoad();
  1107. }
  1108. void IDynamicGrid.InitialiseEditorForm(IDynamicEditorForm editor, object[] items, Func<Type, CoreTable>? pageDataHandler, bool preloadPages)
  1109. {
  1110. InitialiseEditorForm(editor, items.Cast<T>().ToArray(), pageDataHandler, preloadPages);
  1111. }
  1112. public virtual bool EditItems(object[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1113. {
  1114. var values = items.Cast<T>().ToArray();
  1115. return EditItems(values, PageDataHandler, PreloadPages);
  1116. }
  1117. public virtual void InitialiseEditorForm(IDynamicEditorForm editor, T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false)
  1118. {
  1119. var pages = items.Length == 1 ? LoadEditorPages(items.First()) : new DynamicEditorPages();
  1120. var buttons = new DynamicEditorButtons();
  1121. if (items.Length == 1)
  1122. LoadEditorButtons(items.First(), buttons);
  1123. editor.Setup(items.Any() ? items.First().GetType() : typeof(T), pages, buttons, pageDataHandler, preloadPages);
  1124. editor.OnCustomiseColumns = (sender, columns) =>
  1125. {
  1126. columns.Clear();
  1127. columns.AddRange(MasterColumns);
  1128. };
  1129. editor.OnDefineEditor = (o, c) =>
  1130. {
  1131. var result = GetEditor(o, c);
  1132. if (result != null)
  1133. result = result.CloneEditor();
  1134. return result;
  1135. };
  1136. editor.OnFormCustomiseEditor += DoCustomiseEditor;
  1137. editor.OnDefineFilter = (type, column) => { return DefineLookupFilter(type, column, items); };
  1138. //editor.OnDefineFilter += (o, e) => { return DefineFilter(items, e); };
  1139. editor.OnDefineLookups = editor => DefineLookups(editor, items);
  1140. editor.OnEditorValueChanged += (s, n, v) => EditorValueChanged(editor, items, n, v);
  1141. editor.OnAfterEditorValueChanged += (g, args) => AfterEditorValueChanged(g, items, args);
  1142. editor.OnReconfigureEditors = g => DoReconfigureEditors(g, items);
  1143. editor.OnValidateData += (o, i) => ValidateData(items);
  1144. editor.OnSelectPage += SelectPage;
  1145. editor.OnSaveItem = (o, e) =>
  1146. {
  1147. try
  1148. {
  1149. using var Wait = new WaitCursor();
  1150. DoBeforeSave(editor, items);
  1151. if (items.Length == 1)
  1152. editor.UnloadEditorPages(false);
  1153. foreach (var item in items)
  1154. SaveItem(item);
  1155. if (items.Length == 1)
  1156. editor.UnloadEditorPages(true);
  1157. DoAfterSave(editor, items);
  1158. }
  1159. catch (Exception err)
  1160. {
  1161. MessageBox.Show(err.Message);
  1162. e.Cancel = true;
  1163. }
  1164. };
  1165. BeforeLoad(editor, items);
  1166. editor.Items = items;
  1167. AfterLoad(editor, items);
  1168. }
  1169. private void DoCustomiseEditor(IDynamicEditorForm sender, object[] items, DynamicGridColumn column, BaseEditor editor)
  1170. {
  1171. CustomiseEditor((T[])items, column, editor);
  1172. OnCustomiseEditor?.Invoke(sender, (T[])items, column, editor);
  1173. }
  1174. protected virtual void CustomiseEditor(T[] items, DynamicGridColumn column, BaseEditor editor)
  1175. {
  1176. }
  1177. protected virtual void DoAfterSave(IDynamicEditorForm editor, T[] items)
  1178. {
  1179. OnAfterSave?.Invoke(editor, items);
  1180. }
  1181. protected virtual void DoBeforeSave(IDynamicEditorForm editor, T[] items)
  1182. {
  1183. OnBeforeSave?.Invoke(editor, items);
  1184. }
  1185. public virtual bool EditItems(T[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1186. {
  1187. DynamicEditorForm editor;
  1188. using (var cursor = new WaitCursor())
  1189. {
  1190. editor = new DynamicEditorForm();
  1191. editor.SetValue(Panel.ZIndexProperty, 999);
  1192. InitialiseEditorForm(editor, items, PageDataHandler, PreloadPages);
  1193. OnEditorLoaded?.Invoke(editor, items);
  1194. }
  1195. return editor.ShowDialog() == true;
  1196. }
  1197. private Dictionary<String, object?> AfterEditorValueChanged(DynamicEditorGrid grid, T[] items, AfterEditorValueChangedArgs args)
  1198. {
  1199. var changes = new Dictionary<string, object?>();
  1200. OnAfterEditorValueChanged(grid, items, args, changes);
  1201. return changes;
  1202. }
  1203. protected virtual void OnAfterEditorValueChanged(DynamicEditorGrid? grid, T[] items, AfterEditorValueChangedArgs args, Dictionary<String, object?> changes)
  1204. {
  1205. }
  1206. protected virtual void DoReconfigureEditors(DynamicEditorGrid grid, T[] items)
  1207. {
  1208. /*if (items.First() is IDimensioned dimensioned)
  1209. {
  1210. UpdateEditor(grid, x => x.Dimensions.Quantity, dimensioned.Dimensions.GetUnit().HasQuantity);
  1211. UpdateEditor(grid, x => x.Dimensions.Length, dimensioned.Dimensions.GetUnit().HasLength);
  1212. UpdateEditor(grid, x => x.Dimensions.Width, dimensioned.Dimensions.GetUnit().HasWidth);
  1213. UpdateEditor(grid, x => x.Dimensions.Height, dimensioned.Dimensions.GetUnit().HasHeight);
  1214. UpdateEditor(grid, x => x.Dimensions.Weight, dimensioned.Dimensions.GetUnit().HasWeight);
  1215. }*/
  1216. }
  1217. private List<string>? ValidateData(T[] items)
  1218. {
  1219. var errors = new List<string>();
  1220. DoValidate(items, errors);
  1221. OnValidate?.Invoke(this, items, errors);
  1222. return errors.Count != 0 ? errors : null;
  1223. }
  1224. protected virtual void DoValidate(T[] items, List<string> errors)
  1225. {
  1226. }
  1227. protected virtual void AfterLoad(IDynamicEditorForm editor, T[] items)
  1228. {
  1229. editor.AfterLoad();
  1230. }
  1231. protected virtual void SelectPage(object sender, BaseObject[]? items)
  1232. {
  1233. }
  1234. protected virtual Dictionary<string, object?> EditorValueChanged(IDynamicEditorForm editor, T[] items, string name, object value)
  1235. {
  1236. var result = DynamicGridUtils.UpdateEditorValue(items, name, value);
  1237. if (OnEditorValueChanged != null)
  1238. {
  1239. var newchanges = OnEditorValueChanged(editor, name, value);
  1240. foreach (var key in newchanges.Keys)
  1241. result[key] = newchanges[key];
  1242. }
  1243. return result;
  1244. }
  1245. private readonly Dictionary<Tuple<Type, Type>, Dictionary<object, object>> _lookupcache = new();
  1246. protected virtual void DefineLookups(ILookupEditorControl sender, T[] items, bool async = true)
  1247. {
  1248. if (sender.EditorDefinition is not ILookupEditor editor)
  1249. return;
  1250. var colname = sender.ColumnName;
  1251. if (async)
  1252. {
  1253. Task.Run(() =>
  1254. {
  1255. try
  1256. {
  1257. var values = editor.Values(typeof(T), colname, items);
  1258. Dispatcher.Invoke(
  1259. () =>
  1260. {
  1261. try
  1262. {
  1263. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  1264. sender.LoadLookups(values);
  1265. }
  1266. catch (Exception e2)
  1267. {
  1268. Logger.Send(LogType.Information, typeof(T).Name,
  1269. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  1270. }
  1271. }
  1272. );
  1273. }
  1274. catch (Exception e)
  1275. {
  1276. Logger.Send(LogType.Information, typeof(T).Name,
  1277. "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  1278. }
  1279. });
  1280. }
  1281. else
  1282. {
  1283. var values = editor.Values(typeof(T), colname, items);
  1284. sender.LoadLookups(values);
  1285. }
  1286. }
  1287. /// <summary>
  1288. /// Retrieves an editor to display for the given column of <paramref name="item"/>.
  1289. /// </summary>
  1290. /// <param name="item">The object being edited.</param>
  1291. /// <param name="column">The column of the editor.</param>
  1292. /// <returns>A new editor, or <see langword="null"/> if no editor defined and no sensible default exists.</returns>
  1293. protected virtual BaseEditor? GetEditor(object item, DynamicGridColumn column)
  1294. {
  1295. return column.Editor ?? CoreUtils.GetProperty(item.GetType(), column.ColumnName).GetEditor();
  1296. }
  1297. protected IFilter? DefineLookupFilter(Type type, string column, T[] items)
  1298. {
  1299. return LookupFactory.DefineLookupFilter(typeof(T), type, column, items);
  1300. }
  1301. protected virtual void SetEditorValue(object item, string name, object value)
  1302. {
  1303. try
  1304. {
  1305. CoreUtils.SetPropertyValue(item, name, value);
  1306. }
  1307. catch (Exception e)
  1308. {
  1309. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1310. }
  1311. }
  1312. protected virtual object? GetEditorValue(object item, string name)
  1313. {
  1314. return CoreUtils.GetPropertyValue(item, name);
  1315. }
  1316. protected virtual bool CanCreateItems()
  1317. {
  1318. return true;
  1319. }
  1320. private bool AddEditClick(CoreRow[]? rows)
  1321. {
  1322. if (!IsEnabled || bRefreshing)
  1323. return false;
  1324. if (rows == null || rows.Length == 0)
  1325. {
  1326. if (!CanCreateItems())
  1327. return false;
  1328. var item = CreateItem();
  1329. if (!AfterCreate(item))
  1330. return false;
  1331. // Yea, and this won't work, because we're actually usually showing the description of a linked item,
  1332. // not the id of the link, and we need to set the ID to have it work properly :-(
  1333. //foreach (String key in VisualFilters.Keys)
  1334. // CoreUtils.SetPropertyValue(item, key, VisualFilters[key]);
  1335. if (EditItems([item]))
  1336. {
  1337. //_CurrentRow = Data.Rows.Count;
  1338. var row = Data.NewRow();
  1339. ObjectToRow(item, row);
  1340. Data.Rows.Add(row);
  1341. InvalidateGrid();
  1342. SelectedRows = [row];
  1343. DoChanged();
  1344. return true;
  1345. }
  1346. return false;
  1347. }
  1348. var items = Array.Empty<T>();
  1349. using (new WaitCursor())
  1350. {
  1351. Stopwatch sw = new Stopwatch();
  1352. sw.Start();
  1353. items = LoadItems(rows);
  1354. //Logger.Send(LogType.Information, "DG:LoadItems", String.Format("Loaded Items: {0}ms", sw.ElapsedMilliseconds));
  1355. sw.Stop();
  1356. }
  1357. if (items.Length != 0)
  1358. {
  1359. var snaps = items.ToArray(x => x.TakeSnapshot());
  1360. if (EditItems(items))
  1361. {
  1362. var sel = SelectedRows;
  1363. for (var i = 0; i < items.Length; i++)
  1364. UpdateRow(rows[i], items[i]);
  1365. InvalidateGrid();
  1366. SelectedRows = sel;
  1367. DoChanged();
  1368. return true;
  1369. }
  1370. else
  1371. {
  1372. foreach(var snap in snaps)
  1373. {
  1374. snap.ResetObject();
  1375. }
  1376. }
  1377. return false;
  1378. }
  1379. return false;
  1380. }
  1381. #endregion
  1382. #region Duplicate
  1383. protected virtual IEnumerable<T> LoadDuplicatorItems(CoreRow[] rows)
  1384. {
  1385. return LoadItems(rows);
  1386. }
  1387. private bool DoDuplicate(Button button, CoreRow[] rows)
  1388. {
  1389. if (!rows.Any())
  1390. {
  1391. MessageBox.Show("Please select at least one record to duplicate!");
  1392. return false;
  1393. }
  1394. /*var ids = ExtractValues(x => x.ID, Selection.Selected).ToArray();
  1395. if (!ids.Any())
  1396. {
  1397. MessageBox.Show("Please select at least one record to duplicate!");
  1398. return false;
  1399. }*/
  1400. var duplicator = (new T() as IDuplicatable)?.GetDuplicator();
  1401. if (duplicator is null)
  1402. {
  1403. MessageBox.Show($"Cannot duplicate {typeof(T)}");
  1404. return false;
  1405. }
  1406. duplicator.Duplicate(LoadDuplicatorItems(rows));// new Filter<T>(x => x.ID).InList(ids));
  1407. return true;
  1408. }
  1409. #endregion
  1410. public virtual T CreateItem()
  1411. {
  1412. var result = new T();
  1413. OnCreateItem?.Invoke(this, result);
  1414. return result;
  1415. }
  1416. public virtual bool AfterCreate(T item)
  1417. {
  1418. return OnAfterCreateItem?.Invoke(this, item) ?? true;
  1419. }
  1420. protected virtual void DoPrint(object sender)
  1421. {
  1422. OnPrintData?.Invoke(sender);
  1423. }
  1424. protected virtual void ShowHelp(string slug)
  1425. {
  1426. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + slug) { UseShellExecute = true });
  1427. }
  1428. protected void ReloadForms<TTargetType, TTargetForm, TSourceForm>(IDynamicEditorForm editor, TTargetType item,
  1429. Expression<Func<TSourceForm, object?>> sourcekey, Guid sourceid)
  1430. where TTargetType : Entity, new()
  1431. where TTargetForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  1432. where TSourceForm : Entity, IRemotable, IPersistent, IDigitalForm<TTargetType>, new()
  1433. {
  1434. var type = typeof(IDynamicOneToManyGrid<,>).MakeGenericType(typeof(TTargetType), typeof(TTargetForm));
  1435. var page =
  1436. editor.Pages?.FirstOrDefault(x => x.GetType().GetInterfaces().Contains(type)) as IDynamicOneToManyGrid<TTargetType, TTargetForm>;
  1437. if (page != null && item != null)
  1438. {
  1439. if (!page.Ready)
  1440. page.Load(item, null);
  1441. CoreTable table;
  1442. if (sourceid == Guid.Empty)
  1443. {
  1444. table = new CoreTable();
  1445. table.LoadColumns(typeof(TSourceForm));
  1446. }
  1447. else
  1448. {
  1449. table = new Client<TSourceForm>().Query(
  1450. new Filter<TSourceForm>(sourcekey).IsEqualTo(sourceid).And(x => x.Form.AppliesTo)
  1451. .IsEqualTo(typeof(TTargetType).EntityName().Split('.').Last())
  1452. );
  1453. }
  1454. var newforms = new List<TTargetForm>();
  1455. foreach (var row in table.Rows)
  1456. {
  1457. var sourceform = row.ToObject<TSourceForm>();
  1458. var targetform = new TTargetForm();
  1459. targetform.Form.ID = sourceform.Form.ID;
  1460. targetform.Form.Synchronise(sourceform.Form);
  1461. newforms.Add(targetform);
  1462. }
  1463. page.Items.Clear();
  1464. page.LoadItems(newforms.ToArray());
  1465. }
  1466. }
  1467. #region ClipBuffer
  1468. private Tuple<ClipAction, CoreRow[]>? ClipBuffer;
  1469. protected void ResetClipBuffer()
  1470. {
  1471. ClipBuffer = null;
  1472. }
  1473. protected void SetClipBuffer(ClipAction action, CoreRow[] rows)
  1474. {
  1475. ClipBuffer = new Tuple<ClipAction, CoreRow[]>(action, rows);
  1476. }
  1477. private void CutToClipBuffer()
  1478. {
  1479. SetClipBuffer(ClipAction.Cut, SelectedRows);
  1480. InvalidateGrid();
  1481. }
  1482. private void CopyToClipBuffer()
  1483. {
  1484. SetClipBuffer(ClipAction.Copy, SelectedRows);
  1485. InvalidateGrid();
  1486. }
  1487. private void PasteFromClipBuffer()
  1488. {
  1489. if (ClipBuffer == null)
  1490. return;
  1491. if (!ShowSequenceButtons)
  1492. return;
  1493. using (new WaitCursor())
  1494. {
  1495. var updates = ClipBuffer.Item2.Select(x => x.ToObject<T>()).ToList();
  1496. if (BeforePaste(updates, ClipBuffer.Item1))
  1497. {
  1498. var currow = SelectedRows.FirstOrDefault()
  1499. ?? Data.Rows.LastOrDefault();
  1500. var sequence = currow != null ? currow.Get<T, long>(c => ((ISequenceable)c).Sequence) : 0;
  1501. var postrows = Data.Rows.Where(r => !ClipBuffer.Item2.Contains(r) && r.Get<ISequenceable, long>(x => x.Sequence) >= sequence);
  1502. updates.AddRange(LoadItems(postrows.ToArray()));
  1503. foreach (var update in updates)
  1504. {
  1505. sequence++;
  1506. ((ISequenceable)update).Sequence = sequence;
  1507. }
  1508. }
  1509. if (updates.Any())
  1510. {
  1511. SaveItems(updates.ToArray());
  1512. Refresh(false, true);
  1513. }
  1514. }
  1515. }
  1516. protected virtual bool BeforePaste(IEnumerable<T> items, ClipAction action)
  1517. {
  1518. return true;
  1519. }
  1520. private void Cut_Click(object sender, RoutedEventArgs e)
  1521. {
  1522. CutToClipBuffer();
  1523. }
  1524. private void Copy_Click(object sender, RoutedEventArgs e)
  1525. {
  1526. CopyToClipBuffer();
  1527. }
  1528. private void Paste_Click(object sender, RoutedEventArgs e)
  1529. {
  1530. PasteFromClipBuffer();
  1531. }
  1532. #endregion
  1533. protected virtual void ObjectToRow(T obj, CoreRow row)
  1534. {
  1535. row.Table.FillRow(row, obj);
  1536. }
  1537. #region Import / Export
  1538. protected virtual CoreTable LoadImportKeys(String[] fields)
  1539. {
  1540. var result = new CoreTable();
  1541. result.LoadColumns(Columns.None<T>().Add(fields));
  1542. return result;
  1543. }
  1544. protected virtual Guid GetImportID()
  1545. {
  1546. return Guid.Empty;
  1547. }
  1548. protected virtual bool CustomiseImportItem(T item)
  1549. {
  1550. if (IsSequenced)
  1551. ((ISequenceable)item).Sequence = CoreUtils.GenerateSequence();
  1552. return true;
  1553. }
  1554. protected virtual string CustomiseImportFileName(string filename)
  1555. {
  1556. return filename;
  1557. }
  1558. protected virtual void DoImport()
  1559. {
  1560. var list = new DynamicImportList(
  1561. typeof(T),
  1562. GetImportID()
  1563. );
  1564. list.OnImportItem += o => { return CustomiseImportItem((T)o); };
  1565. list.OnCustomiseImport += (o, args) => { args.FileName = CustomiseImportFileName(args.FileName); };
  1566. list.OnSave += (sender, entity) => SaveItem(entity as T);
  1567. list.OnLoad += (sender, type, fields, id) => LoadImportKeys(fields);
  1568. list.ShowDialog();
  1569. Refresh(false, true);
  1570. }
  1571. private void Import_Click(object sender, RoutedEventArgs e)
  1572. {
  1573. DoImport();
  1574. }
  1575. protected virtual void CustomiseExportColumns(List<string> columnnames)
  1576. {
  1577. }
  1578. protected virtual string CustomiseExportFileName(string filename)
  1579. {
  1580. return filename;
  1581. }
  1582. protected virtual void CustomiseExportFilters(Filters<T> filters, CoreRow[] visiblerows)
  1583. {
  1584. }
  1585. protected virtual void ApplyExportFilter(CoreTable table, object data)
  1586. {
  1587. }
  1588. protected virtual void DoExport()
  1589. {
  1590. var columnnames = VisibleColumns.Select(x => x.ColumnName).ToList();
  1591. CustomiseExportColumns(columnnames);
  1592. var form = new DynamicExportForm(typeof(T), columnnames);
  1593. if (form.ShowDialog() != true)
  1594. return;
  1595. var filters = new Filters<T>();
  1596. filters.Add(DefineFilter());
  1597. var predicates = UIComponent.GetFilterPredicates();
  1598. var visiblerows = GetVisibleRows();
  1599. CustomiseExportFilters(filters, visiblerows);
  1600. var columns = Columns.None<T>().Add(form.Fields);
  1601. var otherColumns = form.GetChildFields()
  1602. .Select(x => new Tuple<Type, IColumns>(
  1603. x.Key,
  1604. Columns.None(x.Key).Add(x.Value)))
  1605. .Where(x => x.Item2.ColumnNames().Any()).ToList();
  1606. var reloadColumns = Columns.None<T>();
  1607. foreach (var column in columns)
  1608. {
  1609. reloadColumns.Add(column);
  1610. }
  1611. foreach (var column in HiddenColumns.ColumnNames)
  1612. {
  1613. reloadColumns.Add(column);
  1614. }
  1615. foreach (var (column, _) in predicates)
  1616. {
  1617. reloadColumns.Add(column);
  1618. }
  1619. var sort = LookupFactory.DefineSort<T>();
  1620. Reload(filters, reloadColumns, ref sort, (data, err) => Dispatcher.Invoke(() =>
  1621. {
  1622. if (data is not null)
  1623. {
  1624. var newData = new CoreTable();
  1625. newData.LoadColumns(columns);
  1626. FilterRows(data, newData, filter: row =>
  1627. {
  1628. foreach(var (_, predicate) in predicates)
  1629. {
  1630. if (!predicate(row))
  1631. {
  1632. return false;
  1633. }
  1634. }
  1635. return true;
  1636. });
  1637. var list = new List<Tuple<Type?, CoreTable>>() { new(typeof(T), newData) };
  1638. list.AddRange(LoadExportTables(filters, otherColumns));
  1639. DoExportTables(list);
  1640. }
  1641. else if (err is not null)
  1642. {
  1643. Logger.Send(LogType.Error, "", $"Error in export: {CoreUtils.FormatException(err)}");
  1644. MessageBox.Show(err.Message);
  1645. }
  1646. }));
  1647. }
  1648. private void Export_Click(object sender, RoutedEventArgs e)
  1649. {
  1650. DoExport();
  1651. }
  1652. /// <summary>
  1653. /// Loads the child tables for an export, based on the filter of the parent table.
  1654. /// </summary>
  1655. /// <remarks>
  1656. /// If not overriden, defaults to creating empty tables with no records.
  1657. /// </remarks>
  1658. /// <param name="filter">Filter for the parent table.</param>
  1659. /// <param name="tableColumns">A list of the child table types, with columns to load for each</param>
  1660. /// <returns>A list of tables, in the same order as they came in <paramref name="tableColumns"/></returns>
  1661. protected virtual IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<T> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  1662. {
  1663. return tableColumns.Select(x =>
  1664. {
  1665. var table = new CoreTable();
  1666. table.LoadColumns(x.Item2);
  1667. return new Tuple<Type?, CoreTable>(x.Item1, table);
  1668. });
  1669. }
  1670. private void DoExportTables(List<Tuple<Type?, CoreTable>> data)
  1671. {
  1672. var filename = CustomiseExportFileName(typeof(T).EntityName().Split('.').Last());
  1673. ExcelExporter.DoExport(data, filename);
  1674. }
  1675. #endregion
  1676. public void ScrollIntoView(CoreRow row)
  1677. {
  1678. UIComponent.ScrollIntoView(row);
  1679. }
  1680. #endregion
  1681. #region Custom Buttons
  1682. private Button CreateButton(BitmapImage? image = null, string? text = null, string? tooltip = null)
  1683. {
  1684. var button = new Button();
  1685. button.SetValue(BorderBrushProperty, new SolidColorBrush(Colors.Gray));
  1686. button.SetValue(BorderThicknessProperty, new Thickness(0.75));
  1687. button.Height = 30;
  1688. UpdateButton(button, image, text, tooltip);
  1689. return button;
  1690. }
  1691. public void UpdateButton(Button button, BitmapImage? image, string? text, string? tooltip = null)
  1692. {
  1693. var stackPnl = new StackPanel();
  1694. stackPnl.Orientation = Orientation.Horizontal;
  1695. //stackPnl.Margin = new Thickness(2);
  1696. if (image != null)
  1697. {
  1698. var img = new Image();
  1699. img.Source = image;
  1700. img.Margin = new Thickness(2);
  1701. img.ToolTip = tooltip;
  1702. stackPnl.Children.Add(img);
  1703. }
  1704. if (!string.IsNullOrEmpty(text))
  1705. {
  1706. button.MaxWidth = double.MaxValue;
  1707. var lbl = new Label();
  1708. lbl.Content = text;
  1709. lbl.VerticalAlignment = VerticalAlignment.Stretch;
  1710. lbl.VerticalContentAlignment = VerticalAlignment.Center;
  1711. lbl.Margin = new Thickness(2, 0, 5, 0);
  1712. lbl.ToolTip = ToolTip;
  1713. stackPnl.Children.Add(lbl);
  1714. }
  1715. else
  1716. button.MaxWidth = 30;
  1717. button.Content = stackPnl;
  1718. button.ToolTip = tooltip;
  1719. }
  1720. private bool bFirstButtonAdded = true;
  1721. private bool AnyButtonsVisible()
  1722. {
  1723. if (Add.Visibility != Visibility.Collapsed)
  1724. return true;
  1725. if (Edit.Visibility != Visibility.Collapsed)
  1726. return true;
  1727. /*if (MultiEdit.Visibility != Visibility.Collapsed)
  1728. return true;*/
  1729. if (Export.Visibility != Visibility.Collapsed)
  1730. return true;
  1731. return false;
  1732. }
  1733. public Button AddButton(string? caption, BitmapImage? image, string? tooltip, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1734. {
  1735. var button = CreateButton(image, caption, tooltip);
  1736. button.Margin = position == DynamicGridButtonPosition.Right
  1737. ? new Thickness(2, 2, 0, 0)
  1738. : bFirstButtonAdded && AnyButtonsVisible()
  1739. ? new Thickness(0, 2, 0, 0)
  1740. : new Thickness(0, 2, 2, 0);
  1741. button.Padding = !String.IsNullOrWhiteSpace(caption) ? new Thickness(5, 1, 5, 1) : new Thickness(1);
  1742. button.Tag = action;
  1743. button.Click += Button_Click;
  1744. if (position == DynamicGridButtonPosition.Right)
  1745. RightButtonStack.Children.Add(button);
  1746. else
  1747. LeftButtonStack.Children.Add(button);
  1748. bFirstButtonAdded = false;
  1749. return button;
  1750. }
  1751. public Button AddButton(string? caption, BitmapImage? image, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1752. {
  1753. var result = AddButton(caption, image, null, action, position);
  1754. return result;
  1755. }
  1756. private void Button_Click(object sender, RoutedEventArgs e)
  1757. {
  1758. var button = (Button)sender;
  1759. var action = (DynamicGridButtonClickEvent)button.Tag;
  1760. //CoreRow row = (CurrentRow > -1) && (CurrentRow < Data.Rows.Count) ? Data.Rows[this.CurrentRow] : null;
  1761. if (action.Invoke(button, SelectedRows))
  1762. Refresh(false, true);
  1763. }
  1764. #endregion
  1765. #region Header Actions
  1766. private void SelectColumnsClick()
  1767. {
  1768. var editor = new DynamicGridColumnsEditor(typeof(T));
  1769. editor.DirectEdit = IsDirectEditMode();
  1770. editor.Columns.AddRange(VisibleColumns);
  1771. if (editor.ShowDialog().Equals(true))
  1772. {
  1773. VisibleColumns.Clear();
  1774. VisibleColumns.AddRange(editor.Columns);
  1775. SaveColumns(VisibleColumns);
  1776. //OnSaveColumns?.Invoke(this, editor.Columns);
  1777. Refresh(true, true);
  1778. }
  1779. }
  1780. #endregion
  1781. #region Drag + Drop
  1782. /// <summary>
  1783. /// Handle a number of rows from a different <see cref="DynamicGrid{T}"/> being dragged into this one.
  1784. /// </summary>
  1785. /// <param name="entity">The type of entity that that the rows of <paramref name="table"/> represent.</param>
  1786. /// <param name="table">The data being dragged.</param>
  1787. /// <param name="e"></param>
  1788. protected virtual void OnDragEnd(Type entity, CoreTable table, DragEventArgs e)
  1789. {
  1790. Logger.Send(LogType.Information,"","OnDragEnd");
  1791. }
  1792. /// <summary>
  1793. /// Handle all types of items being dragged onto this grid that aren't handled by <see cref="OnDragEnd(Type, CoreTable, DragEventArgs)"/>,
  1794. /// i.e., data which is not a <see cref="CoreTable"/> from another <see cref="DynamicGrid{T}"/>
  1795. /// </summary>
  1796. /// <remarks>
  1797. /// Can be used to handle files, for example.
  1798. /// </remarks>
  1799. /// <param name="sender"></param>
  1800. /// <param name="e"></param>
  1801. protected virtual void HandleDragDrop(object sender, DragEventArgs e)
  1802. {
  1803. }
  1804. protected virtual void HandleDragOver(object sender, DragEventArgs e)
  1805. {
  1806. }
  1807. protected DragDropEffects DragTable(Type entity, CoreTable table)
  1808. {
  1809. Logger.Send(LogType.Information, "", "DragTable");
  1810. var data = new DataObject();
  1811. data.SetData(DynamicGridUtils.DragFormat, new DynamicGridDragFormat(table.ToDataTable(), entity));
  1812. var effect = DragDrop.DoDragDrop(this, data, DragDropEffects.All);
  1813. return effect;
  1814. }
  1815. protected virtual DragDropEffects OnRowsDragStart(CoreRow[] rows)
  1816. {
  1817. Logger.Send(LogType.Information, "", "OnRowsDragStart");
  1818. var table = new CoreTable();
  1819. table.LoadColumns(Data.Columns);
  1820. table.LoadRows(rows);
  1821. return DragTable(typeof(T), table);
  1822. }
  1823. #endregion
  1824. }
  1825. #region Styling
  1826. public class DynamicGridRowStyle : DynamicGridStyle<VirtualizingCellsControl>
  1827. {
  1828. public DynamicGridRowStyle() : base(null)
  1829. {
  1830. }
  1831. public DynamicGridRowStyle(IDynamicGridStyle source) : base(source)
  1832. {
  1833. }
  1834. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1835. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1836. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1837. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1838. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1839. }
  1840. public class DynamicGridCellStyle : DynamicGridStyle<Control>
  1841. {
  1842. public DynamicGridCellStyle() : base(null)
  1843. {
  1844. }
  1845. public DynamicGridCellStyle(IDynamicGridStyle source) : base(source)
  1846. {
  1847. }
  1848. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1849. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1850. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1851. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1852. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1853. }
  1854. public class GridSelectionControllerExt : GridSelectionController
  1855. {
  1856. public GridSelectionControllerExt(SfDataGrid datagrid)
  1857. : base(datagrid)
  1858. {
  1859. }
  1860. protected override void ProcessSelectedItemChanged(SelectionPropertyChangedHandlerArgs handle)
  1861. {
  1862. base.ProcessSelectedItemChanged(handle);
  1863. if (handle.NewValue != null)
  1864. {
  1865. //this.DataGrid.ScrollInView(this.CurrentCellManager.CurrentRowColumnIndex);
  1866. //int rowIndex = this.CurrentCellManager.CurrentRowColumnIndex.RowIndex;
  1867. var columnIndex = CurrentCellManager.CurrentRowColumnIndex.ColumnIndex;
  1868. var scrollRowIndex = DataGrid.GetVisualContainer().ScrollRows.LastBodyVisibleLineIndex;
  1869. DataGrid.ScrollInView(new RowColumnIndex(scrollRowIndex, columnIndex));
  1870. }
  1871. }
  1872. }
  1873. // Used to render boolean columns (the default "false" value shows what appears to be an intermediate state, which is ugly
  1874. // This should show nothing for false, and a tick in a box for true
  1875. public class BoolToImageConverter : AbstractConverter<bool,ImageSource>
  1876. {
  1877. public ImageSource TrueValue { get; set; }
  1878. public ImageSource FalseValue { get; set; }
  1879. public BoolToImageConverter()
  1880. {
  1881. TrueValue = Wpf.Resources.Bullet_Tick.AsBitmapImage();
  1882. }
  1883. public override ImageSource Convert(bool value)
  1884. {
  1885. return value ? TrueValue : FalseValue;
  1886. }
  1887. public override bool Deconvert(ImageSource value)
  1888. {
  1889. return ImageUtils.IsEqual(value as BitmapImage,TrueValue as BitmapImage);
  1890. }
  1891. }
  1892. public class StringToColorImageConverter : IValueConverter
  1893. {
  1894. private readonly int _height = 50;
  1895. private readonly int _width = 25;
  1896. private readonly Dictionary<string, BitmapImage> cache = new();
  1897. public StringToColorImageConverter(int width, int height)
  1898. {
  1899. _width = width;
  1900. _height = height;
  1901. }
  1902. public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
  1903. {
  1904. var str = value?.ToString();
  1905. if (str is null)
  1906. return null;
  1907. var colorcode = str.TrimStart('#');
  1908. if (!cache.ContainsKey(colorcode))
  1909. {
  1910. var col = ImageUtils.StringToColor(colorcode);
  1911. var bmp = ImageUtils.BitmapFromColor(col, _width, _height, Color.Black);
  1912. cache[colorcode] = bmp.AsBitmapImage();
  1913. }
  1914. var result = cache[colorcode];
  1915. return result;
  1916. }
  1917. public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  1918. {
  1919. return null;
  1920. }
  1921. }
  1922. public class StringArrayConverter : IValueConverter
  1923. {
  1924. object? IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
  1925. {
  1926. if (value is string[] strArray)
  1927. {
  1928. return string.Join("\n", strArray);
  1929. }
  1930. Logger.Send(LogType.Error, "", $"Attempt to convert an object which is not a string array: {value}.");
  1931. return null;
  1932. }
  1933. object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  1934. {
  1935. return value;
  1936. }
  1937. }
  1938. #endregion
  1939. [Serializable]
  1940. class DynamicGridDragFormat
  1941. {
  1942. private string entity;
  1943. public DataTable Table { get; set; }
  1944. public Type Entity { get => CoreUtils.GetEntity(entity); set => entity = value.EntityName(); }
  1945. public DynamicGridDragFormat(DataTable table, Type entity)
  1946. {
  1947. Table = table;
  1948. Entity = entity;
  1949. }
  1950. }