DynamicGrid.cs 86 KB

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