DynamicGrid.cs 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379
  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. #endregion
  553. protected virtual DynamicGridRowStyleSelector<T> GetRowStyleSelector()
  554. {
  555. return new DynamicGridRowStyleSelector<T, DynamicGridRowStyle>();
  556. }
  557. protected virtual DynamicGridStyle GetRowStyle(CoreRow row, DynamicGridStyle style)
  558. {
  559. DynamicGridStyle? result = null;
  560. if (ClipBuffer != null)
  561. if (ClipBuffer.Item2.Contains(row))
  562. {
  563. var bgbrush = style.Background as SolidColorBrush;
  564. var bgcolor = bgbrush != null ? bgbrush.Color : Colors.Transparent;
  565. result = new DynamicGridRowStyle(style);
  566. result.Background = ClipBuffer.Item1 == ClipAction.Cut
  567. ? new SolidColorBrush(bgcolor.MixColors(0.5, Colors.Orchid))
  568. : new SolidColorBrush(bgcolor.MixColors(0.5, Colors.LightGreen));
  569. result.Foreground = new SolidColorBrush(Colors.Gray);
  570. result.FontStyle = FontStyles.Italic;
  571. }
  572. result ??= OnGetRowStyle != null ? OnGetRowStyle(row, style) : style;
  573. return result;
  574. }
  575. protected virtual void BeforeSelection(CancelEventArgs cancel)
  576. {
  577. OnBeforeSelection?.Invoke(cancel);
  578. }
  579. public bool IsReady { get; protected set; }
  580. public UIElement? Header
  581. {
  582. get => _header;
  583. set
  584. {
  585. if (_header is not null && Layout.Children.Contains(_header))
  586. Layout.Children.Remove(_header);
  587. _header = value;
  588. if (_header is not null)
  589. {
  590. _header.SetValue(Grid.RowProperty, 0);
  591. _header.SetValue(Grid.ColumnProperty, 0);
  592. _header.SetValue(Grid.ColumnSpanProperty, 2);
  593. Layout.Children.Add(_header);
  594. }
  595. }
  596. }
  597. /// <summary>
  598. /// Represents the data in the grid. This is <see langword="null"/> until <see cref="Refresh(bool, bool)"/> is called.
  599. /// </summary>
  600. public CoreTable? MasterData { get; set; }
  601. public DynamicGridColumns MasterColumns { get; protected set; }
  602. public DynamicGridColumns VisibleColumns { get; protected set; }
  603. public DynamicActionColumns ActionColumns { get; protected set; }
  604. public CoreTable Data { get; set; }
  605. public class HiddenColumnsList
  606. {
  607. private List<string> Columns { get; set; } = new();
  608. public IEnumerable<string> ColumnNames => Columns;
  609. public void Add(Expression<Func<T, object?>> column) => Add(CoreUtils.GetFullPropertyName(column, "."));
  610. public void Add(IColumn column) => Add(column.Property);
  611. public void Add(string column)
  612. {
  613. if (!Contains(column))
  614. Columns.Add(column);
  615. }
  616. public bool Contains(string column) => Columns.Contains(column);
  617. }
  618. public void AddHiddenColumn(string column) => HiddenColumns.Add(column);
  619. public HiddenColumnsList HiddenColumns { get; }
  620. private static bool IsSequenced => typeof(T).GetInterfaces().Any(x => x.Equals(typeof(ISequenceable)));
  621. public double RowHeight
  622. {
  623. get => UIComponent.RowHeight;
  624. set => UIComponent.RowHeight = value;
  625. }
  626. public double HeaderHeight
  627. {
  628. get => UIComponent.HeaderRowHeight;
  629. set => UIComponent.HeaderRowHeight = value;
  630. }
  631. #region Options
  632. /// <summary>
  633. /// Initialise things like custom buttons; called once during construction.
  634. /// </summary>
  635. protected abstract void Init();
  636. protected abstract void DoReconfigure(FluentList<DynamicGridOption> options);
  637. private bool _hasLoadedOptions = false;
  638. protected virtual void OptionsChanged()
  639. {
  640. var reloadColumns = false;
  641. Help.Visibility = HasOption(DynamicGridOption.ShowHelp) ? Visibility.Visible : Visibility.Collapsed;
  642. Add.Visibility = HasOption(DynamicGridOption.AddRows) ? Visibility.Visible : Visibility.Collapsed;
  643. Edit.Visibility = HasOption(DynamicGridOption.EditRows) ? Visibility.Visible : Visibility.Collapsed;
  644. EditSpacer.Visibility = HasOption(DynamicGridOption.AddRows) || HasOption(DynamicGridOption.EditRows)
  645. ? Visibility.Visible
  646. : Visibility.Collapsed;
  647. Print.Visibility = HasOption(DynamicGridOption.Print) ? Visibility.Visible : Visibility.Collapsed;
  648. PrintSpacer.Visibility = HasOption(DynamicGridOption.Print) ? Visibility.Visible : Visibility.Collapsed;
  649. Cut.Visibility = IsSequenced && HasOption(DynamicGridOption.EditRows) ? Visibility.Visible : Visibility.Collapsed;
  650. Copy.Visibility = IsSequenced && HasOption(DynamicGridOption.EditRows) ? Visibility.Visible : Visibility.Collapsed;
  651. Paste.Visibility = IsSequenced && HasOption(DynamicGridOption.EditRows) ? Visibility.Visible : Visibility.Collapsed;
  652. ClipboardSpacer.Visibility = IsSequenced && HasOption(DynamicGridOption.EditRows) ? Visibility.Visible : Visibility.Collapsed;
  653. Export.Visibility = HasOption(DynamicGridOption.ExportData) ? Visibility.Visible : Visibility.Collapsed;
  654. Import.Visibility = HasOption(DynamicGridOption.ImportData) ? Visibility.Visible : Visibility.Collapsed;
  655. ExportSpacer.Visibility = HasOption(DynamicGridOption.ExportData) || HasOption(DynamicGridOption.ImportData)
  656. ? Visibility.Visible
  657. : Visibility.Collapsed;
  658. SwitchViewBtn.Visibility = HasOption(DynamicGridOption.DirectEdit) ? Visibility.Visible : Visibility.Collapsed;
  659. Count.Visibility = HasOption(DynamicGridOption.RecordCount) ? Visibility.Visible : Visibility.Collapsed;
  660. Delete.Visibility = HasOption(DynamicGridOption.DeleteRows) ? Visibility.Visible : Visibility.Collapsed;
  661. if (up != null)
  662. up.Position = HasOption(DynamicGridOption.EditRows) ? DynamicActionColumnPosition.Start : DynamicActionColumnPosition.Hidden;
  663. if (down != null)
  664. down.Position = HasOption(DynamicGridOption.EditRows) ? DynamicActionColumnPosition.Start : DynamicActionColumnPosition.Hidden;
  665. if (DuplicateBtn != null)
  666. DuplicateBtn.Visibility = Visibility.Collapsed;
  667. reloadColumns = reloadColumns || UIComponent.OptionsChanged();
  668. if(reloadColumns)
  669. {
  670. Refresh(true, false);
  671. }
  672. }
  673. public bool IsDirectEditMode(IEnumerable<DynamicGridOption>? options = null)
  674. {
  675. return HasOption(DynamicGridOption.DirectEdit, options)
  676. && (Settings.ViewMode == DynamicGridSettings.DynamicGridViewMode.DirectEdit
  677. || Settings.ViewMode == DynamicGridSettings.DynamicGridViewMode.Default);
  678. }
  679. private void SwitchView_Click(object sender, RoutedEventArgs e)
  680. {
  681. Settings.ViewMode = Settings.ViewMode switch
  682. {
  683. DynamicGridSettings.DynamicGridViewMode.Default => DynamicGridSettings.DynamicGridViewMode.Normal,
  684. DynamicGridSettings.DynamicGridViewMode.Normal => DynamicGridSettings.DynamicGridViewMode.DirectEdit,
  685. DynamicGridSettings.DynamicGridViewMode.DirectEdit or _ => DynamicGridSettings.DynamicGridViewMode.Normal
  686. };
  687. SaveSettings(Settings);
  688. Reconfigure();
  689. }
  690. public FluentList<DynamicGridOption> Options { get; }
  691. protected void OnReconfigureEvent(FluentList<DynamicGridOption> options)
  692. {
  693. OnReconfigure?.Invoke(options);
  694. }
  695. /// <summary>
  696. /// Configure custom buttons and options.
  697. /// </summary>
  698. public void Reconfigure(FluentList<DynamicGridOption> options)
  699. {
  700. options.BeginUpdate().Clear();
  701. DoReconfigure(options);
  702. OnReconfigureEvent(options);
  703. options.EndUpdate();
  704. if (!_hasLoadedOptions)
  705. {
  706. _hasLoadedOptions = true;
  707. OptionsChanged();
  708. }
  709. }
  710. public void Reconfigure()
  711. {
  712. Reconfigure(Options);
  713. }
  714. public void Reconfigure(ReconfigureEvent onReconfigure)
  715. {
  716. OnReconfigure += onReconfigure;
  717. Reconfigure();
  718. }
  719. public bool HasOption(DynamicGridOption option, IEnumerable<DynamicGridOption>? options = null) => (options ?? Options).Contains(option);
  720. bool IDynamicGrid.HasOption(InABox.DynamicGrid.DynamicGridOption option) => HasOption(option, null);
  721. #endregion
  722. protected virtual DynamicGridSettings LoadSettings()
  723. {
  724. return new DynamicGridSettings();
  725. }
  726. protected virtual void SaveSettings(DynamicGridSettings settings)
  727. {
  728. }
  729. protected virtual void LoadColumnsMenu(ContextMenu menu)
  730. {
  731. }
  732. protected void UpdateCell(int row, string colname, object? value)
  733. {
  734. var coreRow = Data.Rows[row];
  735. coreRow[colname] = value;
  736. UIComponent.UpdateCell(coreRow, colname, value);
  737. }
  738. private void EntityChanged(T obj, CoreRow row, string changedColumn, Dictionary<string, object?> changes)
  739. {
  740. OnAfterEditorValueChanged(null, new T[] { obj }, new AfterEditorValueChangedArgs(changedColumn, changes), changes);
  741. SaveItem(obj);
  742. foreach (var (key, value) in changes)
  743. {
  744. row[key] = value;
  745. }
  746. UIComponent.UpdateRow(row);
  747. }
  748. #region Row Selections
  749. protected CoreRow[] GetVisibleRows()
  750. {
  751. return UIComponent.GetVisibleRows();
  752. }
  753. public CoreRow[] SelectedRows
  754. {
  755. get => UIComponent.SelectedRows;
  756. set => UIComponent.SelectedRows = value;
  757. }
  758. /// <summary>
  759. /// Call the <see cref="OnSelectItem"/> event, and do any updating which needs to occur when items are selected.
  760. /// </summary>
  761. /// <param name="rows"></param>
  762. protected virtual void SelectItems(CoreRow[]? rows)
  763. {
  764. if (IsReady)
  765. OnSelectItem?.Invoke(this, new DynamicGridSelectionEventArgs(rows));
  766. DuplicateBtn.Visibility =
  767. typeof(T).IsAssignableTo(typeof(IDuplicatable)) && rows != null && rows.Length >= 1 ? Visibility.Visible : Visibility.Collapsed;
  768. }
  769. protected virtual void DoDoubleClick(object sender, DynamicGridCellClickEventArgs args)
  770. {
  771. if (IsDirectEditMode())
  772. return;
  773. //SelectItems(SelectedRows);
  774. var e = new HandledEventArgs(false);
  775. OnDoubleClick?.Invoke(sender, e);
  776. if (e.Handled)
  777. return;
  778. if (HasOption(DynamicGridOption.EditRows))
  779. DoEdit();
  780. }
  781. #endregion
  782. #region Column Handling
  783. protected virtual DynamicGridColumns LoadColumns()
  784. {
  785. var result = new DynamicGridColumns();
  786. var cols = IsDirectEditMode()
  787. ? new Columns<T>().Default(ColumnType.IncludeForeignKeys, ColumnType.ExcludeID)
  788. : new Columns<T>().Default(ColumnType.IncludeLinked, ColumnType.ExcludeID);
  789. result.AddRange(MasterColumns.Where(x => cols.Items.Any(c => c.Property.Equals(x.ColumnName)))
  790. .OrderBy(x => CoreUtils.GetPropertySequence(typeof(T), x.ColumnName)));
  791. return result;
  792. }
  793. /// <summary>
  794. /// Provide a set of columns which is the default for this grid.
  795. /// </summary>
  796. public virtual DynamicGridColumns GenerateColumns()
  797. {
  798. var columns = new DynamicGridColumns();
  799. var cols = IsDirectEditMode()
  800. ? new Columns<T>().Default(ColumnType.IncludeForeignKeys, ColumnType.ExcludeID)
  801. : new Columns<T>().Default(ColumnType.IncludeLinked, ColumnType.ExcludeID);
  802. if (cols != null)
  803. {
  804. foreach (var col in cols.Items)
  805. {
  806. var mc = MasterColumns.FirstOrDefault(x => x.ColumnName.Equals(col.Property));
  807. if (mc != null && mc.Editor is not NullEditor && mc.Editor.Visible != Visible.Hidden)
  808. columns.Add(mc);
  809. }
  810. }
  811. return columns;
  812. }
  813. private bool SwapRows(int row1, int row2)
  814. {
  815. CoreRow[] rows = Data.Rows.Where(x => x.Index.Equals(row1) || x.Index.Equals(row2)).ToArray();
  816. var items = LoadItems(rows);
  817. var first = (items.First() as ISequenceable)!;
  818. var last = (items.Last() as ISequenceable)!;
  819. var iBuf1 = first.Sequence;
  820. var iBuf2 = last.Sequence;
  821. first.Sequence = iBuf2;
  822. last.Sequence = iBuf1;
  823. SaveItems(items);
  824. return true;
  825. }
  826. protected virtual void SaveColumns(DynamicGridColumns columns)
  827. {
  828. }
  829. public int DesiredWidth()
  830. {
  831. return UIComponent.DesiredWidth();
  832. }
  833. public virtual void ConfigureColumns(DynamicGridColumns columns)
  834. {
  835. DoCustomiseColumnsEvent(this,columns);
  836. }
  837. private void ReloadColumns()
  838. {
  839. ConfigureColumns(MasterColumns /*, false */);
  840. VisibleColumns = LoadColumns();
  841. ConfigureColumns(VisibleColumns /*, true */);
  842. UIComponent.RefreshColumns(VisibleColumns, ActionColumns);
  843. }
  844. #endregion
  845. #region Refresh / Reload
  846. protected abstract void Reload(Filters<T> criteria, Columns<T> columns, ref SortOrder<T>? sort, Action<CoreTable?, Exception?> action);
  847. public Filter<T>? DefineFilter()
  848. {
  849. if (OnDefineFilter is null)
  850. return null;
  851. var result = OnDefineFilter.Invoke(typeof(T)) as Filter<T>;
  852. return result;
  853. }
  854. protected virtual bool FilterRecord(CoreRow row)
  855. {
  856. var bOK = ActionColumns.All(x =>
  857. {
  858. return x.FilterRecord is null || x.SelectedFilters is null || !x.SelectedFilters.Any()
  859. || x.FilterRecord.Invoke(row, x.SelectedFilters);
  860. });
  861. if (bOK && OnFilterRecord is not null)
  862. bOK = OnFilterRecord(row);
  863. return bOK;
  864. }
  865. public IEnumerable<TType> ExtractValues<TType>(Expression<Func<T, TType>> column, Selection selection)
  866. {
  867. var result = selection == Selection.None
  868. ? Enumerable.Empty<TType>()
  869. : selection == Selection.Selected
  870. ? SelectedRows.Select(r => r.Get(column))
  871. : Data.ExtractValues(column);
  872. return result;
  873. }
  874. public virtual void Refresh(bool reloadcolumns, bool reloaddata)
  875. {
  876. if (bRefreshing)
  877. return;
  878. if (!DoBeforeRefresh())
  879. return;
  880. UIComponent.BeforeRefresh();
  881. var cursor = UseWaitCursor ? new WaitCursor() : null;
  882. Loading.Visibility = Visibility.Visible;
  883. Loading.BeginAnimation(Label.OpacityProperty, LoadingFader);
  884. bRefreshing = true;
  885. if (reloadcolumns)
  886. ReloadColumns();
  887. if (reloaddata)
  888. {
  889. _lookupcache.Clear();
  890. var criteria = new Filters<T>();
  891. var filter = DefineFilter();
  892. if (filter != null)
  893. criteria.Add(filter);
  894. var columns = DataColumns();
  895. var sort = LookupFactory.DefineSort<T>();
  896. if (sort == null && IsSequenced)
  897. sort = new SortOrder<T>("Sequence");
  898. Reload(
  899. criteria
  900. , columns
  901. , ref sort
  902. , (table, exception) =>
  903. {
  904. if (exception != null)
  905. {
  906. Dispatcher.Invoke(() =>
  907. {
  908. MessageWindow.ShowError("Sorry! We couldn't load the data.", exception);
  909. });
  910. }
  911. else if (table is not null)
  912. {
  913. MasterData = table;
  914. Dispatcher.Invoke(() =>
  915. {
  916. ProcessData();
  917. DoAfterRefresh();
  918. bRefreshing = false;
  919. IsReady = true;
  920. });
  921. }
  922. }
  923. );
  924. }
  925. else
  926. {
  927. ProcessData();
  928. DoAfterRefresh();
  929. bRefreshing = false;
  930. IsReady = true;
  931. Loading.BeginAnimation(Label.OpacityProperty, null);
  932. Loading.Visibility = Visibility.Collapsed;
  933. }
  934. if (cursor != null)
  935. {
  936. cursor.Dispose();
  937. cursor = null;
  938. }
  939. }
  940. protected void NotifyBeforeRefresh(BeforeRefreshEventArgs args) => BeforeRefresh?.Invoke(this, args);
  941. protected void NotifyAfterRefresh(AfterRefreshEventArgs args) => AfterRefresh?.Invoke(this, args);
  942. protected bool OnBeforeRefresh()
  943. {
  944. return true;
  945. }
  946. private bool DoBeforeRefresh()
  947. {
  948. var result = OnBeforeRefresh();
  949. if (result)
  950. {
  951. var args = new BeforeRefreshEventArgs() { Cancel = false };
  952. NotifyBeforeRefresh(args);
  953. result = args.Cancel == false;
  954. }
  955. return result;
  956. }
  957. protected virtual void OnAfterRefresh()
  958. {
  959. }
  960. protected void DoAfterRefresh()
  961. {
  962. OnAfterRefresh();
  963. NotifyAfterRefresh(new AfterRefreshEventArgs());
  964. }
  965. public Columns<T> DataColumns()
  966. {
  967. var columns = new Columns<T>();
  968. foreach (var column in VisibleColumns)
  969. columns.Add(column.ColumnName);
  970. foreach (var column in HiddenColumns.ColumnNames)
  971. columns.Add(new Column<T>(column));
  972. return columns;
  973. }
  974. private void ProcessData()
  975. {
  976. Data.Columns.Clear();
  977. Data.Setters.Clear();
  978. if (MasterData != null)
  979. foreach (var column in MasterData.Columns)
  980. Data.Columns.Add(column);
  981. LoadData();
  982. }
  983. protected readonly Dictionary<CoreRow, CoreRow> _recordmap = new();
  984. public void UpdateRow<TRow, TType>(CoreRow row, Expression<Func<TRow, TType>> column, TType value, bool refresh = true)
  985. {
  986. row.Set(column, value);
  987. _recordmap[row].Set(column, value);
  988. if (refresh)
  989. InvalidateRow(row);
  990. }
  991. public void UpdateRow<TType>(CoreRow row, string column, TType value, bool refresh = true)
  992. {
  993. row.Set(column, value);
  994. _recordmap[row].Set(column, value);
  995. if (refresh)
  996. InvalidateRow(row);
  997. }
  998. public void UpdateRow(CoreRow row, T obj)
  999. {
  1000. ObjectToRow(obj, row);
  1001. ObjectToRow(obj, _recordmap[row]);
  1002. }
  1003. public void AddRow(CoreRow row)
  1004. {
  1005. if (MasterData is null) return;
  1006. var masterrow = MasterData.NewRow();
  1007. MasterData.FillRow(masterrow, row);
  1008. Refresh(false, false);
  1009. }
  1010. public void AddRow(T data)
  1011. {
  1012. if (MasterData is null) return;
  1013. MasterData.LoadRow(data);
  1014. Refresh(false, false);
  1015. }
  1016. public void DeleteRow(CoreRow row)
  1017. {
  1018. if (MasterData is null) return;
  1019. var masterrow = _recordmap[row];
  1020. MasterData.Rows.Remove(masterrow);
  1021. Refresh(false, false);
  1022. }
  1023. private void FilterRows(CoreTable from, CoreTable into, Dictionary<CoreRow, CoreRow>? recordMap = null, Func<CoreRow, bool>? filter = null)
  1024. {
  1025. into.Rows.Clear();
  1026. recordMap?.Clear();
  1027. foreach (var row in from.Rows.ToArray())
  1028. if (FilterRecord(row) && filter?.Invoke(row) != false)
  1029. {
  1030. var newrow = into.NewRow();
  1031. for (var i = 0; i < into.Columns.Count; i++)
  1032. {
  1033. var value = i < row.Values.Count ? row.Values[i] : null;
  1034. if (into.Columns[i].DataType.IsNumeric())
  1035. value = into.Columns[i].DataType.IsDefault(value) ? null : value;
  1036. //else if (Data.Columns[i].DataType == typeof(String[]))
  1037. // value = String.Join("\n", value as String[]);
  1038. newrow.Values.Add(value);
  1039. }
  1040. //newrow.Values.AddRange(row.Values);
  1041. //if ((OnFilterRecord == null) || (OnFilterRecord(row)))
  1042. into.Rows.Add(newrow);
  1043. recordMap?.TryAdd(newrow, row);
  1044. }
  1045. }
  1046. private void LoadData()
  1047. {
  1048. ResetClipBuffer();
  1049. if (MasterData is null)
  1050. return;
  1051. FilterRows(MasterData, Data, _recordmap);
  1052. InvalidateGrid();
  1053. //ScrollBar.Value = _CurrentRow <= 0 ? 0 : _CurrentRow;
  1054. SelectedRows = Array.Empty<CoreRow>();
  1055. }
  1056. //IncrementalList<T> _data = null;
  1057. public void InvalidateRow(CoreRow row)
  1058. {
  1059. UIComponent.InvalidateRow(row);
  1060. }
  1061. protected void InvalidateGrid()
  1062. {
  1063. if (RowStyleSelector != null)
  1064. RowStyleSelector.Data = Data;
  1065. UIComponent.RefreshData(Data);
  1066. Loading.BeginAnimation(Label.OpacityProperty, null);
  1067. Loading.Visibility = Visibility.Collapsed;
  1068. }
  1069. public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  1070. {
  1071. UIComponent.AddVisualFilter(column, value, filtertype);
  1072. }
  1073. #endregion
  1074. #region Item Manipulation
  1075. #region Load/Save/Delete
  1076. public virtual T[] LoadItems(CoreRow[] rows)
  1077. {
  1078. var result = new List<T>();
  1079. foreach (var row in rows)
  1080. {
  1081. var index = Data.Rows.IndexOf(row);
  1082. result.Add(LoadItem(row));
  1083. }
  1084. return result.ToArray();
  1085. }
  1086. public abstract T LoadItem(CoreRow row);
  1087. public abstract void SaveItem(T item);
  1088. public virtual void SaveItems(T[] items)
  1089. {
  1090. foreach (var item in items)
  1091. SaveItem(item);
  1092. }
  1093. protected virtual bool CanDeleteItems(params CoreRow[] rows)
  1094. {
  1095. return true;
  1096. }
  1097. public abstract void DeleteItems(params CoreRow[] rows);
  1098. protected virtual void DoDelete()
  1099. {
  1100. var rows = SelectedRows.ToArray();
  1101. if (rows.Any())
  1102. if (CanDeleteItems(rows))
  1103. if (MessageBox.Show("Are you sure you wish to delete the selected records?", "Confirm Delete", MessageBoxButton.YesNo) ==
  1104. MessageBoxResult.Yes)
  1105. {
  1106. DeleteItems(rows);
  1107. SelectedRows = Array.Empty<CoreRow>();
  1108. OnChanged?.Invoke(this, EventArgs.Empty);
  1109. Refresh(false, true);
  1110. SelectItems(null);
  1111. }
  1112. }
  1113. private void Delete_Click(object sender, RoutedEventArgs e)
  1114. {
  1115. DoDelete();
  1116. }
  1117. #endregion
  1118. #region Edit
  1119. protected virtual void DoEdit()
  1120. {
  1121. if (SelectedRows.Length == 0)
  1122. return;
  1123. if (AddEditClick(SelectedRows))
  1124. {
  1125. SelectItems(SelectedRows);
  1126. }
  1127. }
  1128. private void Edit_Click(object sender, RoutedEventArgs e)
  1129. {
  1130. DoEdit();
  1131. }
  1132. protected virtual void DoAdd(bool OpenEditorOnDirectEdit = false)
  1133. {
  1134. //CoreRow row = (SelectedRow > -1) && (SelectedRow < Data.Rows.Count) ? Data.Rows[this.SelectedRow] : null;
  1135. if (IsDirectEditMode() && !OpenEditorOnDirectEdit)
  1136. {
  1137. var item = CreateItem();
  1138. if (!AfterCreate(item))
  1139. return;
  1140. SaveItem(item);
  1141. var datarow = Data.NewRow();
  1142. ObjectToRow(item, datarow);
  1143. Data.Rows.Add(datarow);
  1144. var masterrow = MasterData.NewRow();
  1145. ObjectToRow(item, masterrow);
  1146. MasterData.Rows.Add(masterrow);
  1147. _recordmap[datarow] = masterrow;
  1148. InvalidateGrid();
  1149. SelectedRows = new[] { datarow };
  1150. OnChanged?.Invoke(this, EventArgs.Empty);
  1151. }
  1152. else if (AddEditClick(null))
  1153. {
  1154. Refresh(false, true);
  1155. }
  1156. }
  1157. private void Add_Click(object sender, RoutedEventArgs e)
  1158. {
  1159. if (CanCreateItems())
  1160. DoAdd();
  1161. }
  1162. public virtual DynamicEditorPages LoadEditorPages(T item)
  1163. {
  1164. DynamicEditorPages pages = new DynamicEditorPages();
  1165. DynamicGridUtils.LoadOneToManyPages(typeof(T), pages);
  1166. DynamicGridUtils.LoadEnclosedListPages(typeof(T), pages);
  1167. DynamicGridUtils.LoadManyToManyPages(typeof(T), pages);
  1168. DynamicGridUtils.LoadCustomEditorPages(typeof(T), pages);
  1169. foreach (var page in pages)
  1170. page.Ready = false;
  1171. return pages;
  1172. }
  1173. public virtual void LoadEditorButtons(T item, DynamicEditorButtons buttons)
  1174. {
  1175. buttons.Clear();
  1176. buttons.Add(
  1177. "",
  1178. Wpf.Resources.help.AsBitmapImage(),
  1179. item,
  1180. (f, i) =>
  1181. {
  1182. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + typeof(T).Name.SplitCamelCase().Replace(" ", "_"))
  1183. { UseShellExecute = true });
  1184. }
  1185. );
  1186. OnLoadEditorButtons?.Invoke(item, buttons);
  1187. }
  1188. protected virtual void BeforeLoad(IDynamicEditorForm form, T[] items)
  1189. {
  1190. form.BeforeLoad();
  1191. }
  1192. void IDynamicGrid.InitialiseEditorForm(IDynamicEditorForm editor, object[] items, Func<Type, CoreTable>? pageDataHandler, bool preloadPages)
  1193. {
  1194. InitialiseEditorForm(editor, items.Cast<T>().ToArray(), pageDataHandler, preloadPages);
  1195. }
  1196. public virtual bool EditItems(object[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1197. {
  1198. var values = items.Cast<T>().ToArray();
  1199. return EditItems(values, PageDataHandler, PreloadPages);
  1200. }
  1201. public virtual void InitialiseEditorForm(IDynamicEditorForm editor, T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false)
  1202. {
  1203. var pages = items.Length == 1 ? LoadEditorPages(items.First()) : new DynamicEditorPages();
  1204. var buttons = new DynamicEditorButtons();
  1205. if (items.Length == 1)
  1206. LoadEditorButtons(items.First(), buttons);
  1207. editor.Setup(items.Any() ? items.First().GetType() : typeof(T), pages, buttons, pageDataHandler, preloadPages);
  1208. editor.OnCustomiseColumns = (sender, columns) =>
  1209. {
  1210. columns.Clear();
  1211. columns.AddRange(MasterColumns);
  1212. ConfigureColumns(columns);
  1213. };
  1214. editor.OnDefineEditor = (o, c) =>
  1215. {
  1216. var result = GetEditor(o, c);
  1217. if (result != null)
  1218. result = result.CloneEditor();
  1219. return result;
  1220. };
  1221. editor.OnFormCustomiseEditor += DoCustomiseEditor;
  1222. editor.OnDefineFilter = (type, column) => { return DefineLookupFilter(type, column, items); };
  1223. //editor.OnDefineFilter += (o, e) => { return DefineFilter(items, e); };
  1224. editor.OnDefineLookups = editor => DefineLookups(editor, items);
  1225. editor.OnEditorValueChanged += (s, n, v) => EditorValueChanged(editor, items, n, v);
  1226. editor.OnAfterEditorValueChanged += (g, args) => AfterEditorValueChanged(g, items, args);
  1227. editor.OnReconfigureEditors = g => DoReconfigureEditors(g, items);
  1228. editor.OnValidateData += (o, i) => ValidateData(items);
  1229. editor.OnSelectPage += SelectPage;
  1230. editor.OnSaveItem = (o, e) =>
  1231. {
  1232. try
  1233. {
  1234. using var Wait = new WaitCursor();
  1235. DoBeforeSave(editor, items);
  1236. if (items.Length == 1)
  1237. editor.UnloadEditorPages(false);
  1238. foreach (var item in items)
  1239. SaveItem(item);
  1240. if (items.Length == 1)
  1241. editor.UnloadEditorPages(true);
  1242. DoAfterSave(editor, items);
  1243. }
  1244. catch (Exception err)
  1245. {
  1246. MessageBox.Show(err.Message);
  1247. e.Cancel = true;
  1248. }
  1249. };
  1250. BeforeLoad(editor, items);
  1251. editor.Items = items;
  1252. AfterLoad(editor, items);
  1253. }
  1254. private void DoCustomiseEditor(IDynamicEditorForm sender, object[] items, DynamicGridColumn column, BaseEditor editor)
  1255. {
  1256. CustomiseEditor((T[])items, column, editor);
  1257. OnCustomiseEditor?.Invoke(sender, (T[])items, column, editor);
  1258. }
  1259. protected virtual void CustomiseEditor(T[] items, DynamicGridColumn column, BaseEditor editor)
  1260. {
  1261. }
  1262. protected virtual void DoAfterSave(IDynamicEditorForm editor, T[] items)
  1263. {
  1264. OnAfterSave?.Invoke(editor, items);
  1265. }
  1266. protected virtual void DoBeforeSave(IDynamicEditorForm editor, T[] items)
  1267. {
  1268. OnBeforeSave?.Invoke(editor, items);
  1269. }
  1270. public virtual bool EditItems(T[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1271. {
  1272. DynamicEditorForm editor;
  1273. using (var cursor = new WaitCursor())
  1274. {
  1275. editor = new DynamicEditorForm();
  1276. editor.SetValue(Panel.ZIndexProperty, 999);
  1277. InitialiseEditorForm(editor, items, PageDataHandler, PreloadPages);
  1278. OnEditorLoaded?.Invoke(editor, items);
  1279. }
  1280. return editor.ShowDialog() == true;
  1281. }
  1282. private Dictionary<String, object?> AfterEditorValueChanged(DynamicEditorGrid grid, T[] items, AfterEditorValueChangedArgs args)
  1283. {
  1284. var changes = new Dictionary<string, object?>();
  1285. OnAfterEditorValueChanged(grid, items, args, changes);
  1286. return changes;
  1287. }
  1288. protected virtual void OnAfterEditorValueChanged(DynamicEditorGrid? grid, T[] items, AfterEditorValueChangedArgs args, Dictionary<String, object?> changes)
  1289. {
  1290. }
  1291. protected virtual void DoReconfigureEditors(DynamicEditorGrid grid, T[] items)
  1292. {
  1293. /*if (items.First() is IDimensioned dimensioned)
  1294. {
  1295. UpdateEditor(grid, x => x.Dimensions.Quantity, dimensioned.Dimensions.GetUnit().HasQuantity);
  1296. UpdateEditor(grid, x => x.Dimensions.Length, dimensioned.Dimensions.GetUnit().HasLength);
  1297. UpdateEditor(grid, x => x.Dimensions.Width, dimensioned.Dimensions.GetUnit().HasWidth);
  1298. UpdateEditor(grid, x => x.Dimensions.Height, dimensioned.Dimensions.GetUnit().HasHeight);
  1299. UpdateEditor(grid, x => x.Dimensions.Weight, dimensioned.Dimensions.GetUnit().HasWeight);
  1300. }*/
  1301. }
  1302. private string[]? ValidateData(T[] items)
  1303. {
  1304. var errors = new List<string>();
  1305. DoValidate(items, errors);
  1306. OnValidate?.Invoke(this, items, errors);
  1307. return errors.Any() ? errors.ToArray() : null;
  1308. }
  1309. protected virtual void DoValidate(T[] items, List<string> errors)
  1310. {
  1311. }
  1312. protected virtual void AfterLoad(IDynamicEditorForm editor, T[] items)
  1313. {
  1314. editor.AfterLoad();
  1315. }
  1316. protected virtual void SelectPage(object sender, BaseObject[]? items)
  1317. {
  1318. }
  1319. protected virtual Dictionary<string, object?> EditorValueChanged(IDynamicEditorForm editor, T[] items, string name, object value)
  1320. {
  1321. var result = DynamicGridUtils.UpdateEditorValue(items, name, value);
  1322. if (OnEditorValueChanged != null)
  1323. {
  1324. var newchanges = OnEditorValueChanged(editor, name, value);
  1325. foreach (var key in newchanges.Keys)
  1326. result[key] = newchanges[key];
  1327. }
  1328. return result;
  1329. }
  1330. private readonly Dictionary<Tuple<Type, Type>, Dictionary<object, object>> _lookupcache = new();
  1331. protected virtual void DefineLookups(ILookupEditorControl sender, T[] items, bool async = true)
  1332. {
  1333. if (sender.EditorDefinition is not ILookupEditor editor)
  1334. return;
  1335. var colname = sender.ColumnName;
  1336. if (async)
  1337. {
  1338. Task.Run(() =>
  1339. {
  1340. try
  1341. {
  1342. var values = editor.Values(typeof(T), colname, items);
  1343. Dispatcher.Invoke(
  1344. () =>
  1345. {
  1346. try
  1347. {
  1348. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  1349. sender.LoadLookups(values);
  1350. }
  1351. catch (Exception e2)
  1352. {
  1353. Logger.Send(LogType.Information, typeof(T).Name,
  1354. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  1355. }
  1356. }
  1357. );
  1358. }
  1359. catch (Exception e)
  1360. {
  1361. Logger.Send(LogType.Information, typeof(T).Name,
  1362. "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  1363. }
  1364. });
  1365. }
  1366. else
  1367. {
  1368. var values = editor.Values(typeof(T), colname, items);
  1369. sender.LoadLookups(values);
  1370. }
  1371. }
  1372. /// <summary>
  1373. /// Retrieves an editor to display for the given column of <paramref name="item"/>.
  1374. /// </summary>
  1375. /// <param name="item">The object being edited.</param>
  1376. /// <param name="column">The column of the editor.</param>
  1377. /// <returns>A new editor, or <see langword="null"/> if no editor defined and no sensible default exists.</returns>
  1378. protected virtual BaseEditor? GetEditor(object item, DynamicGridColumn column)
  1379. {
  1380. return column.Editor ?? CoreUtils.GetProperty(item.GetType(), column.ColumnName).GetEditor();
  1381. }
  1382. protected IFilter? DefineLookupFilter(Type type, string column, T[] items)
  1383. {
  1384. return LookupFactory.DefineLookupFilter(typeof(T), type, column, items);
  1385. }
  1386. protected virtual void SetEditorValue(object item, string name, object value)
  1387. {
  1388. try
  1389. {
  1390. CoreUtils.SetPropertyValue(item, name, value);
  1391. }
  1392. catch (Exception e)
  1393. {
  1394. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1395. }
  1396. }
  1397. protected virtual object? GetEditorValue(object item, string name)
  1398. {
  1399. return CoreUtils.GetPropertyValue(item, name);
  1400. }
  1401. protected virtual bool CanCreateItems()
  1402. {
  1403. return true;
  1404. }
  1405. private bool AddEditClick(CoreRow[]? rows)
  1406. {
  1407. if (!IsEnabled || bRefreshing)
  1408. return false;
  1409. if (rows == null || !rows.Any())
  1410. {
  1411. if (!CanCreateItems())
  1412. return false;
  1413. var item = CreateItem();
  1414. if (!AfterCreate(item))
  1415. return false;
  1416. // Yea, and this won't work, because we're actually usually showing the description of a linked item,
  1417. // not the id of the link, and we need to set the ID to have it work properly :-(
  1418. //foreach (String key in VisualFilters.Keys)
  1419. // CoreUtils.SetPropertyValue(item, key, VisualFilters[key]);
  1420. if (EditItems([item]))
  1421. {
  1422. //_CurrentRow = Data.Rows.Count;
  1423. var row = Data.NewRow();
  1424. ObjectToRow(item, row);
  1425. Data.Rows.Add(row);
  1426. InvalidateGrid();
  1427. SelectedRows = [row];
  1428. DoChanged();
  1429. return true;
  1430. }
  1431. return false;
  1432. }
  1433. var items = Array.Empty<T>();
  1434. using (new WaitCursor())
  1435. {
  1436. Stopwatch sw = new Stopwatch();
  1437. sw.Start();
  1438. items = LoadItems(rows);
  1439. //Logger.Send(LogType.Information, "DG:LoadItems", String.Format("Loaded Items: {0}ms", sw.ElapsedMilliseconds));
  1440. sw.Stop();
  1441. }
  1442. if (items.Length != 0)
  1443. {
  1444. var sel = SelectedRows;
  1445. if (EditItems(items))
  1446. {
  1447. for (var i = 0; i < items.Length; i++)
  1448. {
  1449. UpdateRow(rows[i], items[i]);
  1450. }
  1451. InvalidateGrid();
  1452. SelectedRows = sel;
  1453. DoChanged();
  1454. return true;
  1455. }
  1456. return false;
  1457. }
  1458. return false;
  1459. }
  1460. #endregion
  1461. #region Duplicate
  1462. protected virtual IEnumerable<T> LoadDuplicatorItems(CoreRow[] rows)
  1463. {
  1464. return LoadItems(rows);
  1465. }
  1466. private bool DoDuplicate(Button button, CoreRow[] rows)
  1467. {
  1468. if (!rows.Any())
  1469. {
  1470. MessageBox.Show("Please select at least one record to duplicate!");
  1471. return false;
  1472. }
  1473. /*var ids = ExtractValues(x => x.ID, Selection.Selected).ToArray();
  1474. if (!ids.Any())
  1475. {
  1476. MessageBox.Show("Please select at least one record to duplicate!");
  1477. return false;
  1478. }*/
  1479. var duplicator = (new T() as IDuplicatable)?.GetDuplicator();
  1480. if (duplicator is null)
  1481. {
  1482. MessageBox.Show($"Cannot duplicate {typeof(T)}");
  1483. return false;
  1484. }
  1485. duplicator.Duplicate(LoadDuplicatorItems(rows));// new Filter<T>(x => x.ID).InList(ids));
  1486. return true;
  1487. }
  1488. #endregion
  1489. public virtual T CreateItem()
  1490. {
  1491. var result = new T();
  1492. OnCreateItem?.Invoke(this, result);
  1493. return result;
  1494. }
  1495. public virtual bool AfterCreate(T item)
  1496. {
  1497. return OnAfterCreateItem?.Invoke(this, item) ?? true;
  1498. }
  1499. protected virtual void DoPrint(object sender)
  1500. {
  1501. OnPrintData?.Invoke(sender);
  1502. }
  1503. protected virtual void ShowHelp(string slug)
  1504. {
  1505. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + slug) { UseShellExecute = true });
  1506. }
  1507. protected void ReloadForms<TTargetType, TTargetForm, TSourceForm>(IDynamicEditorForm editor, TTargetType item,
  1508. Expression<Func<TSourceForm, object?>> sourcekey, Guid sourceid)
  1509. where TTargetType : Entity, new()
  1510. where TTargetForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  1511. where TSourceForm : Entity, IRemotable, IPersistent, IDigitalForm<TTargetType>, new()
  1512. {
  1513. var type = typeof(IDynamicOneToManyGrid<,>).MakeGenericType(typeof(TTargetType), typeof(TTargetForm));
  1514. var page =
  1515. editor.Pages?.FirstOrDefault(x => x.GetType().GetInterfaces().Contains(type)) as IDynamicOneToManyGrid<TTargetType, TTargetForm>;
  1516. if (page != null && item != null)
  1517. {
  1518. if (!page.Ready)
  1519. page.Load(item, null);
  1520. CoreTable table;
  1521. if (sourceid == Guid.Empty)
  1522. {
  1523. table = new CoreTable();
  1524. table.LoadColumns(typeof(TSourceForm));
  1525. }
  1526. else
  1527. {
  1528. table = new Client<TSourceForm>().Query(
  1529. new Filter<TSourceForm>(sourcekey).IsEqualTo(sourceid).And(x => x.Form.AppliesTo)
  1530. .IsEqualTo(typeof(TTargetType).EntityName().Split('.').Last())
  1531. );
  1532. }
  1533. var newforms = new List<TTargetForm>();
  1534. foreach (var row in table.Rows)
  1535. {
  1536. var sourceform = row.ToObject<TSourceForm>();
  1537. var targetform = new TTargetForm();
  1538. targetform.Form.ID = sourceform.Form.ID;
  1539. targetform.Form.Synchronise(sourceform.Form);
  1540. newforms.Add(targetform);
  1541. }
  1542. page.Items.Clear();
  1543. page.LoadItems(newforms.ToArray());
  1544. }
  1545. }
  1546. #region ClipBuffer
  1547. private Tuple<ClipAction, CoreRow[]>? ClipBuffer;
  1548. protected void ResetClipBuffer()
  1549. {
  1550. ClipBuffer = null;
  1551. }
  1552. protected void SetClipBuffer(ClipAction action, CoreRow[] rows)
  1553. {
  1554. ClipBuffer = new Tuple<ClipAction, CoreRow[]>(action, rows);
  1555. }
  1556. private void CutToClipBuffer()
  1557. {
  1558. SetClipBuffer(ClipAction.Cut, SelectedRows);
  1559. InvalidateGrid();
  1560. }
  1561. private void CopyToClipBuffer()
  1562. {
  1563. SetClipBuffer(ClipAction.Copy, SelectedRows);
  1564. InvalidateGrid();
  1565. }
  1566. private void PasteFromClipBuffer()
  1567. {
  1568. if (ClipBuffer == null)
  1569. return;
  1570. if (!IsSequenced)
  1571. return;
  1572. using (new WaitCursor())
  1573. {
  1574. var updates = ClipBuffer.Item2.Select(x => x.ToObject<T>()).ToList();
  1575. if (BeforePaste(updates, ClipBuffer.Item1))
  1576. {
  1577. var currow = SelectedRows.FirstOrDefault()
  1578. ?? Data.Rows.LastOrDefault();
  1579. var sequence = currow != null ? currow.Get<T, long>(c => ((ISequenceable)c).Sequence) : 0;
  1580. var postrows = Data.Rows.Where(r => !ClipBuffer.Item2.Contains(r) && r.Get<ISequenceable, long>(x => x.Sequence) >= sequence);
  1581. updates.AddRange(LoadItems(postrows.ToArray()));
  1582. foreach (var update in updates)
  1583. {
  1584. sequence++;
  1585. ((ISequenceable)update).Sequence = sequence;
  1586. }
  1587. }
  1588. if (updates.Any())
  1589. {
  1590. SaveItems(updates.ToArray());
  1591. Refresh(false, true);
  1592. }
  1593. }
  1594. }
  1595. protected virtual bool BeforePaste(IEnumerable<T> items, ClipAction action)
  1596. {
  1597. return true;
  1598. }
  1599. private void Cut_Click(object sender, RoutedEventArgs e)
  1600. {
  1601. CutToClipBuffer();
  1602. }
  1603. private void Copy_Click(object sender, RoutedEventArgs e)
  1604. {
  1605. CopyToClipBuffer();
  1606. }
  1607. private void Paste_Click(object sender, RoutedEventArgs e)
  1608. {
  1609. PasteFromClipBuffer();
  1610. }
  1611. #endregion
  1612. protected virtual void ObjectToRow(T obj, CoreRow row)
  1613. {
  1614. row.Table.FillRow(row, obj);
  1615. }
  1616. #region Import / Export
  1617. protected virtual CoreTable LoadImportKeys(String[] fields)
  1618. {
  1619. var result = new CoreTable();
  1620. result.LoadColumns(new Columns<T>(fields));
  1621. return result;
  1622. }
  1623. protected virtual Guid GetImportID()
  1624. {
  1625. return Guid.Empty;
  1626. }
  1627. protected virtual bool CustomiseImportItem(T item)
  1628. {
  1629. if (IsSequenced)
  1630. ((ISequenceable)item).Sequence = CoreUtils.GenerateSequence();
  1631. return true;
  1632. }
  1633. protected virtual string CustomiseImportFileName(string filename)
  1634. {
  1635. return filename;
  1636. }
  1637. protected virtual void DoImport()
  1638. {
  1639. var list = new DynamicImportList(
  1640. typeof(T),
  1641. GetImportID()
  1642. );
  1643. list.OnImportItem += o => { return CustomiseImportItem((T)o); };
  1644. list.OnCustomiseImport += (o, args) => { args.FileName = CustomiseImportFileName(args.FileName); };
  1645. list.OnSave += (sender, entity) => SaveItem(entity as T);
  1646. list.OnLoad += (sender, type, fields, id) => LoadImportKeys(fields);
  1647. list.ShowDialog();
  1648. Refresh(false, true);
  1649. }
  1650. private void Import_Click(object sender, RoutedEventArgs e)
  1651. {
  1652. DoImport();
  1653. }
  1654. protected virtual void CustomiseExportColumns(List<string> columnnames)
  1655. {
  1656. }
  1657. protected virtual string CustomiseExportFileName(string filename)
  1658. {
  1659. return filename;
  1660. }
  1661. protected virtual void CustomiseExportFilters(Filters<T> filters, CoreRow[] visiblerows)
  1662. {
  1663. }
  1664. protected virtual void ApplyExportFilter(CoreTable table, object data)
  1665. {
  1666. }
  1667. protected virtual void DoExport()
  1668. {
  1669. var columnnames = VisibleColumns.Select(x => x.ColumnName).ToList();
  1670. CustomiseExportColumns(columnnames);
  1671. var form = new DynamicExportForm(typeof(T), columnnames);
  1672. if (form.ShowDialog() != true)
  1673. return;
  1674. var filters = new Filters<T>();
  1675. filters.Add(DefineFilter());
  1676. var predicates = UIComponent.GetFilterPredicates();
  1677. var visiblerows = GetVisibleRows();
  1678. CustomiseExportFilters(filters, visiblerows);
  1679. var columns = new Columns<T>(form.Fields);
  1680. var otherColumns = form.GetChildFields()
  1681. .Select(x => new Tuple<Type, IColumns>(
  1682. x.Key,
  1683. (Activator.CreateInstance(typeof(Columns<>).MakeGenericType(x.Key), new object[] { x.Value }) as IColumns)!))
  1684. .Where(x => x.Item2.ColumnNames().Any()).ToList();
  1685. var reloadColumns = new Columns<T>();
  1686. foreach (var column in columns.ColumnNames())
  1687. {
  1688. reloadColumns.Add(column);
  1689. }
  1690. foreach (var column in HiddenColumns.ColumnNames)
  1691. {
  1692. reloadColumns.Add(column);
  1693. }
  1694. foreach (var (column, _) in predicates)
  1695. {
  1696. reloadColumns.Add(column);
  1697. }
  1698. var sort = LookupFactory.DefineSort<T>();
  1699. Reload(filters, reloadColumns, ref sort, (data, err) => Dispatcher.Invoke(() =>
  1700. {
  1701. if (data is not null)
  1702. {
  1703. var newData = new CoreTable();
  1704. foreach (var column in columns.Items)
  1705. newData.Columns.Add(new CoreColumn { ColumnName = column.Property, DataType = column.Type });
  1706. FilterRows(data, newData, filter: row =>
  1707. {
  1708. foreach(var (_, predicate) in predicates)
  1709. {
  1710. if (!predicate(row))
  1711. {
  1712. return false;
  1713. }
  1714. }
  1715. return true;
  1716. });
  1717. var list = new List<Tuple<Type?, CoreTable>>() { new(typeof(T), newData) };
  1718. list.AddRange(LoadExportTables(filters, otherColumns));
  1719. DoExportTables(list);
  1720. }
  1721. else if (err is not null)
  1722. {
  1723. Logger.Send(LogType.Error, "", $"Error in export: {CoreUtils.FormatException(err)}");
  1724. MessageBox.Show(err.Message);
  1725. }
  1726. }));
  1727. }
  1728. private void Export_Click(object sender, RoutedEventArgs e)
  1729. {
  1730. DoExport();
  1731. }
  1732. /// <summary>
  1733. /// Loads the child tables for an export, based on the filter of the parent table.
  1734. /// </summary>
  1735. /// <remarks>
  1736. /// If not overriden, defaults to creating empty tables with no records.
  1737. /// </remarks>
  1738. /// <param name="filter">Filter for the parent table.</param>
  1739. /// <param name="tableColumns">A list of the child table types, with columns to load for each</param>
  1740. /// <returns>A list of tables, in the same order as they came in <paramref name="tableColumns"/></returns>
  1741. protected virtual IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<T> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  1742. {
  1743. return tableColumns.Select(x =>
  1744. {
  1745. var table = new CoreTable();
  1746. table.LoadColumns(x.Item2);
  1747. return new Tuple<Type?, CoreTable>(x.Item1, table);
  1748. });
  1749. }
  1750. private void DoExportTables(List<Tuple<Type?, CoreTable>> data)
  1751. {
  1752. var filename = CustomiseExportFileName(typeof(T).EntityName().Split('.').Last());
  1753. ExcelExporter.DoExport(data, filename);
  1754. }
  1755. #endregion
  1756. public void ScrollIntoView(CoreRow row)
  1757. {
  1758. UIComponent.ScrollIntoView(row);
  1759. }
  1760. #endregion
  1761. #region Custom Buttons
  1762. private Button CreateButton(BitmapImage? image = null, string? text = null, string? tooltip = null)
  1763. {
  1764. var button = new Button();
  1765. button.SetValue(BorderBrushProperty, new SolidColorBrush(Colors.Gray));
  1766. button.SetValue(BorderThicknessProperty, new Thickness(0.75));
  1767. button.Height = 30;
  1768. UpdateButton(button, image, text, tooltip);
  1769. return button;
  1770. }
  1771. public void UpdateButton(Button button, BitmapImage? image, string? text, string? tooltip = null)
  1772. {
  1773. var stackPnl = new StackPanel();
  1774. stackPnl.Orientation = Orientation.Horizontal;
  1775. //stackPnl.Margin = new Thickness(2);
  1776. if (image != null)
  1777. {
  1778. var img = new Image();
  1779. img.Source = image;
  1780. img.Margin = new Thickness(2);
  1781. img.ToolTip = tooltip;
  1782. stackPnl.Children.Add(img);
  1783. }
  1784. if (!string.IsNullOrEmpty(text))
  1785. {
  1786. button.MaxWidth = double.MaxValue;
  1787. var lbl = new Label();
  1788. lbl.Content = text;
  1789. lbl.VerticalAlignment = VerticalAlignment.Stretch;
  1790. lbl.VerticalContentAlignment = VerticalAlignment.Center;
  1791. lbl.Margin = new Thickness(2, 0, 5, 0);
  1792. lbl.ToolTip = ToolTip;
  1793. stackPnl.Children.Add(lbl);
  1794. }
  1795. else
  1796. button.MaxWidth = 30;
  1797. button.Content = stackPnl;
  1798. button.ToolTip = tooltip;
  1799. }
  1800. private bool bFirstButtonAdded = true;
  1801. private bool AnyButtonsVisible()
  1802. {
  1803. if (Add.Visibility != Visibility.Collapsed)
  1804. return true;
  1805. if (Edit.Visibility != Visibility.Collapsed)
  1806. return true;
  1807. /*if (MultiEdit.Visibility != Visibility.Collapsed)
  1808. return true;*/
  1809. if (Export.Visibility != Visibility.Collapsed)
  1810. return true;
  1811. return false;
  1812. }
  1813. public Button AddButton(string? caption, BitmapImage? image, string? tooltip, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1814. {
  1815. var button = CreateButton(image, caption, tooltip);
  1816. button.Margin = position == DynamicGridButtonPosition.Right
  1817. ? new Thickness(2, 2, 0, 0)
  1818. : bFirstButtonAdded && AnyButtonsVisible()
  1819. ? new Thickness(0, 2, 0, 0)
  1820. : new Thickness(0, 2, 2, 0);
  1821. button.Padding = !String.IsNullOrWhiteSpace(caption) ? new Thickness(5, 1, 5, 1) : new Thickness(1);
  1822. button.Tag = action;
  1823. button.Click += Button_Click;
  1824. if (position == DynamicGridButtonPosition.Right)
  1825. RightButtonStack.Children.Add(button);
  1826. else
  1827. LeftButtonStack.Children.Add(button);
  1828. bFirstButtonAdded = false;
  1829. return button;
  1830. }
  1831. public Button AddButton(string? caption, BitmapImage? image, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1832. {
  1833. var result = AddButton(caption, image, null, action, position);
  1834. return result;
  1835. }
  1836. private void Button_Click(object sender, RoutedEventArgs e)
  1837. {
  1838. var button = (Button)sender;
  1839. var action = (DynamicGridButtonClickEvent)button.Tag;
  1840. //CoreRow row = (CurrentRow > -1) && (CurrentRow < Data.Rows.Count) ? Data.Rows[this.CurrentRow] : null;
  1841. if (action.Invoke(button, SelectedRows))
  1842. Refresh(false, true);
  1843. }
  1844. #endregion
  1845. #region Header Actions
  1846. private void SelectColumnsClick()
  1847. {
  1848. var editor = new DynamicGridColumnsEditor(typeof(T));
  1849. editor.DirectEdit = IsDirectEditMode();
  1850. editor.Columns.AddRange(VisibleColumns);
  1851. if (editor.ShowDialog().Equals(true))
  1852. {
  1853. VisibleColumns.Clear();
  1854. VisibleColumns.AddRange(editor.Columns);
  1855. SaveColumns(VisibleColumns);
  1856. //OnSaveColumns?.Invoke(this, editor.Columns);
  1857. Refresh(true, true);
  1858. }
  1859. }
  1860. #endregion
  1861. #region Drag + Drop
  1862. /// <summary>
  1863. /// Handle a number of rows from a different <see cref="DynamicGrid{T}"/> being dragged into this one.
  1864. /// </summary>
  1865. /// <param name="entity">The type of entity that that the rows of <paramref name="table"/> represent.</param>
  1866. /// <param name="table">The data being dragged.</param>
  1867. /// <param name="e"></param>
  1868. protected virtual void OnDragEnd(Type entity, CoreTable table, DragEventArgs e)
  1869. {
  1870. Logger.Send(LogType.Information,"","OnDragEnd");
  1871. }
  1872. /// <summary>
  1873. /// Handle all types of items being dragged onto this grid that aren't handled by <see cref="OnDragEnd(Type, CoreTable, DragEventArgs)"/>,
  1874. /// i.e., data which is not a <see cref="CoreTable"/> from another <see cref="DynamicGrid{T}"/>
  1875. /// </summary>
  1876. /// <remarks>
  1877. /// Can be used to handle files, for example.
  1878. /// </remarks>
  1879. /// <param name="sender"></param>
  1880. /// <param name="e"></param>
  1881. protected virtual void HandleDragDrop(object sender, DragEventArgs e)
  1882. {
  1883. }
  1884. protected virtual void HandleDragOver(object sender, DragEventArgs e)
  1885. {
  1886. }
  1887. protected DragDropEffects DragTable(Type entity, CoreTable table)
  1888. {
  1889. Logger.Send(LogType.Information, "", "DragTable");
  1890. var data = new DataObject();
  1891. data.SetData(DynamicGridUtils.DragFormat, new DynamicGridDragFormat(table.ToDataTable(), entity));
  1892. var effect = DragDrop.DoDragDrop(this, data, DragDropEffects.All);
  1893. return effect;
  1894. }
  1895. protected virtual DragDropEffects OnRowsDragStart(CoreRow[] rows)
  1896. {
  1897. Logger.Send(LogType.Information, "", "OnRowsDragStart");
  1898. var table = new CoreTable();
  1899. table.LoadColumns(Data.Columns);
  1900. table.LoadRows(rows);
  1901. return DragTable(typeof(T), table);
  1902. }
  1903. #endregion
  1904. }