DynamicGrid.cs 75 KB

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