DynamicGrid.cs 84 KB

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