DynamicGrid.cs 75 KB

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