DynamicGrid.cs 75 KB

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