DynamicGrid.cs 87 KB

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