DynamicGrid.cs 75 KB

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