DynamicGrid.cs 85 KB

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