DynamicGrid.cs 75 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374
  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 AddRow(CoreRow row)
  999. {
  1000. if (MasterData is null) return;
  1001. var masterrow = MasterData.NewRow();
  1002. MasterData.FillRow(masterrow, row);
  1003. Refresh(false, false);
  1004. }
  1005. public void AddRow(T data)
  1006. {
  1007. if (MasterData is null) return;
  1008. MasterData.LoadRow(data);
  1009. Refresh(false, false);
  1010. }
  1011. public void DeleteRow(CoreRow row)
  1012. {
  1013. if (MasterData is null) return;
  1014. var masterrow = _recordmap[row];
  1015. MasterData.Rows.Remove(masterrow);
  1016. Refresh(false, false);
  1017. }
  1018. private void FilterRows(CoreTable from, CoreTable into, Dictionary<CoreRow, CoreRow>? recordMap = null, Func<CoreRow, bool>? filter = null)
  1019. {
  1020. into.Rows.Clear();
  1021. recordMap?.Clear();
  1022. foreach (var row in from.Rows.ToArray())
  1023. if (FilterRecord(row) && filter?.Invoke(row) != false)
  1024. {
  1025. var newrow = into.NewRow();
  1026. for (var i = 0; i < into.Columns.Count; i++)
  1027. {
  1028. var value = i < row.Values.Count ? row.Values[i] : null;
  1029. if (into.Columns[i].DataType.IsNumeric())
  1030. value = into.Columns[i].DataType.IsDefault(value) ? null : value;
  1031. //else if (Data.Columns[i].DataType == typeof(String[]))
  1032. // value = String.Join("\n", value as String[]);
  1033. newrow.Values.Add(value);
  1034. }
  1035. //newrow.Values.AddRange(row.Values);
  1036. //if ((OnFilterRecord == null) || (OnFilterRecord(row)))
  1037. into.Rows.Add(newrow);
  1038. recordMap?.TryAdd(newrow, row);
  1039. }
  1040. }
  1041. private void LoadData()
  1042. {
  1043. ResetClipBuffer();
  1044. if (MasterData is null)
  1045. return;
  1046. FilterRows(MasterData, Data, _recordmap);
  1047. InvalidateGrid();
  1048. //ScrollBar.Value = _CurrentRow <= 0 ? 0 : _CurrentRow;
  1049. SelectedRows = Array.Empty<CoreRow>();
  1050. }
  1051. //IncrementalList<T> _data = null;
  1052. public void InvalidateRow(CoreRow row)
  1053. {
  1054. UIComponent.InvalidateRow(row);
  1055. }
  1056. protected void InvalidateGrid()
  1057. {
  1058. if (RowStyleSelector != null)
  1059. RowStyleSelector.Data = Data;
  1060. UIComponent.RefreshData(Data);
  1061. Loading.BeginAnimation(Label.OpacityProperty, null);
  1062. Loading.Visibility = Visibility.Collapsed;
  1063. }
  1064. public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  1065. {
  1066. UIComponent.AddVisualFilter(column, value, filtertype);
  1067. }
  1068. #endregion
  1069. #region Item Manipulation
  1070. #region Load/Save/Delete
  1071. public virtual T[] LoadItems(CoreRow[] rows)
  1072. {
  1073. var result = new List<T>();
  1074. foreach (var row in rows)
  1075. {
  1076. var index = Data.Rows.IndexOf(row);
  1077. result.Add(LoadItem(row));
  1078. }
  1079. return result.ToArray();
  1080. }
  1081. public abstract T LoadItem(CoreRow row);
  1082. public abstract void SaveItem(T item);
  1083. public virtual void SaveItems(T[] items)
  1084. {
  1085. foreach (var item in items)
  1086. SaveItem(item);
  1087. }
  1088. protected virtual bool CanDeleteItems(params CoreRow[] rows)
  1089. {
  1090. return true;
  1091. }
  1092. public abstract void DeleteItems(params CoreRow[] rows);
  1093. protected virtual void DoDelete()
  1094. {
  1095. var rows = SelectedRows.ToArray();
  1096. if (rows.Any())
  1097. if (CanDeleteItems(rows))
  1098. if (MessageBox.Show("Are you sure you wish to delete the selected records?", "Confirm Delete", MessageBoxButton.YesNo) ==
  1099. MessageBoxResult.Yes)
  1100. {
  1101. DeleteItems(rows);
  1102. SelectedRows = Array.Empty<CoreRow>();
  1103. OnChanged?.Invoke(this, EventArgs.Empty);
  1104. Refresh(false, true);
  1105. SelectItems(null);
  1106. }
  1107. }
  1108. private void Delete_Click(object sender, RoutedEventArgs e)
  1109. {
  1110. DoDelete();
  1111. }
  1112. #endregion
  1113. #region Edit
  1114. protected virtual void DoEdit()
  1115. {
  1116. if (SelectedRows.Length == 0)
  1117. return;
  1118. if (AddEditClick(SelectedRows))
  1119. {
  1120. SelectItems(SelectedRows);
  1121. }
  1122. }
  1123. private void Edit_Click(object sender, RoutedEventArgs e)
  1124. {
  1125. DoEdit();
  1126. }
  1127. protected virtual void DoAdd(bool OpenEditorOnDirectEdit = false)
  1128. {
  1129. //CoreRow row = (SelectedRow > -1) && (SelectedRow < Data.Rows.Count) ? Data.Rows[this.SelectedRow] : null;
  1130. if (IsDirectEditMode() && !OpenEditorOnDirectEdit)
  1131. {
  1132. var item = CreateItem();
  1133. if (!AfterCreate(item))
  1134. return;
  1135. SaveItem(item);
  1136. var datarow = Data.NewRow();
  1137. ObjectToRow(item, datarow);
  1138. Data.Rows.Add(datarow);
  1139. var masterrow = MasterData.NewRow();
  1140. ObjectToRow(item, masterrow);
  1141. MasterData.Rows.Add(masterrow);
  1142. _recordmap[datarow] = masterrow;
  1143. InvalidateGrid();
  1144. SelectedRows = new[] { datarow };
  1145. OnChanged?.Invoke(this, EventArgs.Empty);
  1146. }
  1147. else if (AddEditClick(null))
  1148. {
  1149. Refresh(false, true);
  1150. }
  1151. }
  1152. private void Add_Click(object sender, RoutedEventArgs e)
  1153. {
  1154. if (CanCreateItems())
  1155. DoAdd();
  1156. }
  1157. public virtual DynamicEditorPages LoadEditorPages(T item)
  1158. {
  1159. DynamicEditorPages pages = new DynamicEditorPages();
  1160. DynamicGridUtils.LoadOneToManyPages(typeof(T), pages);
  1161. DynamicGridUtils.LoadEnclosedListPages(typeof(T), pages);
  1162. DynamicGridUtils.LoadManyToManyPages(typeof(T), pages);
  1163. DynamicGridUtils.LoadCustomEditorPages(typeof(T), pages);
  1164. foreach (var page in pages)
  1165. page.Ready = false;
  1166. return pages;
  1167. }
  1168. public virtual void LoadEditorButtons(T item, DynamicEditorButtons buttons)
  1169. {
  1170. buttons.Clear();
  1171. buttons.Add(
  1172. "",
  1173. Wpf.Resources.help.AsBitmapImage(),
  1174. item,
  1175. (f, i) =>
  1176. {
  1177. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + typeof(T).Name.SplitCamelCase().Replace(" ", "_"))
  1178. { UseShellExecute = true });
  1179. }
  1180. );
  1181. OnLoadEditorButtons?.Invoke(item, buttons);
  1182. }
  1183. protected virtual void BeforeLoad(IDynamicEditorForm form, T[] items)
  1184. {
  1185. form.BeforeLoad();
  1186. }
  1187. void IDynamicGrid.InitialiseEditorForm(IDynamicEditorForm editor, object[] items, Func<Type, CoreTable>? pageDataHandler, bool preloadPages)
  1188. {
  1189. InitialiseEditorForm(editor, items.Cast<T>().ToArray(), pageDataHandler, preloadPages);
  1190. }
  1191. public virtual bool EditItems(object[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1192. {
  1193. var values = items.Cast<T>().ToArray();
  1194. return EditItems(values, PageDataHandler, PreloadPages);
  1195. }
  1196. public virtual void InitialiseEditorForm(IDynamicEditorForm editor, T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false)
  1197. {
  1198. var pages = items.Length == 1 ? LoadEditorPages(items.First()) : new DynamicEditorPages();
  1199. var buttons = new DynamicEditorButtons();
  1200. if (items.Length == 1)
  1201. LoadEditorButtons(items.First(), buttons);
  1202. editor.Setup(items.Any() ? items.First().GetType() : typeof(T), pages, buttons, pageDataHandler, preloadPages);
  1203. editor.OnCustomiseColumns = (sender, columns) =>
  1204. {
  1205. columns.Clear();
  1206. columns.AddRange(MasterColumns);
  1207. ConfigureColumns(columns);
  1208. };
  1209. editor.OnDefineEditor = (o, c) =>
  1210. {
  1211. var result = GetEditor(o, c);
  1212. if (result != null)
  1213. result = result.CloneEditor();
  1214. return result;
  1215. };
  1216. editor.OnFormCustomiseEditor += DoCustomiseEditor;
  1217. editor.OnDefineFilter = (type, column) => { return DefineLookupFilter(type, column, items); };
  1218. //editor.OnDefineFilter += (o, e) => { return DefineFilter(items, e); };
  1219. editor.OnDefineLookups = editor => DefineLookups(editor, items);
  1220. editor.OnEditorValueChanged += (s, n, v) => EditorValueChanged(editor, items, n, v);
  1221. editor.OnAfterEditorValueChanged += (g, args) => AfterEditorValueChanged(g, items, args);
  1222. editor.OnReconfigureEditors = g => DoReconfigureEditors(g, items);
  1223. editor.OnValidateData += (o, i) => ValidateData(items);
  1224. editor.OnSelectPage += SelectPage;
  1225. editor.OnSaveItem = (o, e) =>
  1226. {
  1227. try
  1228. {
  1229. using var Wait = new WaitCursor();
  1230. DoBeforeSave(editor, items);
  1231. if (items.Length == 1)
  1232. editor.UnloadEditorPages(false);
  1233. foreach (var item in items)
  1234. SaveItem(item);
  1235. if (items.Length == 1)
  1236. editor.UnloadEditorPages(true);
  1237. DoAfterSave(editor, items);
  1238. }
  1239. catch (Exception err)
  1240. {
  1241. MessageBox.Show(err.Message);
  1242. e.Cancel = true;
  1243. }
  1244. };
  1245. BeforeLoad(editor, items);
  1246. editor.Items = items;
  1247. AfterLoad(editor, items);
  1248. }
  1249. private void DoCustomiseEditor(IDynamicEditorForm sender, object[] items, DynamicGridColumn column, BaseEditor editor)
  1250. {
  1251. CustomiseEditor((T[])items, column, editor);
  1252. OnCustomiseEditor?.Invoke(sender, (T[])items, column, editor);
  1253. }
  1254. protected virtual void CustomiseEditor(T[] items, DynamicGridColumn column, BaseEditor editor)
  1255. {
  1256. }
  1257. protected virtual void DoAfterSave(IDynamicEditorForm editor, T[] items)
  1258. {
  1259. OnAfterSave?.Invoke(editor, items);
  1260. }
  1261. protected virtual void DoBeforeSave(IDynamicEditorForm editor, T[] items)
  1262. {
  1263. OnBeforeSave?.Invoke(editor, items);
  1264. }
  1265. public virtual bool EditItems(T[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  1266. {
  1267. DynamicEditorForm editor;
  1268. using (var cursor = new WaitCursor())
  1269. {
  1270. editor = new DynamicEditorForm();
  1271. editor.SetValue(Panel.ZIndexProperty, 999);
  1272. InitialiseEditorForm(editor, items, PageDataHandler, PreloadPages);
  1273. OnEditorLoaded?.Invoke(editor, items);
  1274. }
  1275. return editor.ShowDialog() == true;
  1276. }
  1277. private Dictionary<String, object?> AfterEditorValueChanged(DynamicEditorGrid grid, T[] items, AfterEditorValueChangedArgs args)
  1278. {
  1279. var changes = new Dictionary<string, object?>();
  1280. OnAfterEditorValueChanged(grid, items, args, changes);
  1281. return changes;
  1282. }
  1283. protected virtual void OnAfterEditorValueChanged(DynamicEditorGrid? grid, T[] items, AfterEditorValueChangedArgs args, Dictionary<String, object?> changes)
  1284. {
  1285. }
  1286. protected virtual void DoReconfigureEditors(DynamicEditorGrid grid, T[] items)
  1287. {
  1288. /*if (items.First() is IDimensioned dimensioned)
  1289. {
  1290. UpdateEditor(grid, x => x.Dimensions.Quantity, dimensioned.Dimensions.GetUnit().HasQuantity);
  1291. UpdateEditor(grid, x => x.Dimensions.Length, dimensioned.Dimensions.GetUnit().HasLength);
  1292. UpdateEditor(grid, x => x.Dimensions.Width, dimensioned.Dimensions.GetUnit().HasWidth);
  1293. UpdateEditor(grid, x => x.Dimensions.Height, dimensioned.Dimensions.GetUnit().HasHeight);
  1294. UpdateEditor(grid, x => x.Dimensions.Weight, dimensioned.Dimensions.GetUnit().HasWeight);
  1295. }*/
  1296. }
  1297. private string[]? ValidateData(T[] items)
  1298. {
  1299. var errors = new List<string>();
  1300. DoValidate(items, errors);
  1301. OnValidate?.Invoke(this, items, errors);
  1302. return errors.Any() ? errors.ToArray() : null;
  1303. }
  1304. protected virtual void DoValidate(T[] items, List<string> errors)
  1305. {
  1306. }
  1307. protected virtual void AfterLoad(IDynamicEditorForm editor, T[] items)
  1308. {
  1309. editor.AfterLoad();
  1310. }
  1311. protected virtual void SelectPage(object sender, BaseObject[]? items)
  1312. {
  1313. }
  1314. protected virtual Dictionary<string, object?> EditorValueChanged(IDynamicEditorForm editor, T[] items, string name, object value)
  1315. {
  1316. var result = DynamicGridUtils.UpdateEditorValue(items, name, value);
  1317. if (OnEditorValueChanged != null)
  1318. {
  1319. var newchanges = OnEditorValueChanged(editor, name, value);
  1320. foreach (var key in newchanges.Keys)
  1321. result[key] = newchanges[key];
  1322. }
  1323. return result;
  1324. }
  1325. private readonly Dictionary<Tuple<Type, Type>, Dictionary<object, object>> _lookupcache = new();
  1326. protected virtual void DefineLookups(ILookupEditorControl sender, T[] items, bool async = true)
  1327. {
  1328. if (sender.EditorDefinition is not ILookupEditor editor)
  1329. return;
  1330. var colname = sender.ColumnName;
  1331. if (async)
  1332. {
  1333. Task.Run(() =>
  1334. {
  1335. try
  1336. {
  1337. var values = editor.Values(typeof(T), colname, items);
  1338. Dispatcher.Invoke(
  1339. () =>
  1340. {
  1341. try
  1342. {
  1343. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  1344. sender.LoadLookups(values);
  1345. }
  1346. catch (Exception e2)
  1347. {
  1348. Logger.Send(LogType.Information, typeof(T).Name,
  1349. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  1350. }
  1351. }
  1352. );
  1353. }
  1354. catch (Exception e)
  1355. {
  1356. Logger.Send(LogType.Information, typeof(T).Name,
  1357. "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  1358. }
  1359. });
  1360. }
  1361. else
  1362. {
  1363. var values = editor.Values(typeof(T), colname, items);
  1364. sender.LoadLookups(values);
  1365. }
  1366. }
  1367. /// <summary>
  1368. /// Retrieves an editor to display for the given column of <paramref name="item"/>.
  1369. /// </summary>
  1370. /// <param name="item">The object being edited.</param>
  1371. /// <param name="column">The column of the editor.</param>
  1372. /// <returns>A new editor, or <see langword="null"/> if no editor defined and no sensible default exists.</returns>
  1373. protected virtual BaseEditor? GetEditor(object item, DynamicGridColumn column)
  1374. {
  1375. return column.Editor ?? CoreUtils.GetProperty(item.GetType(), column.ColumnName).GetEditor();
  1376. }
  1377. protected IFilter? DefineLookupFilter(Type type, string column, T[] items)
  1378. {
  1379. return LookupFactory.DefineLookupFilter(typeof(T), type, column, items);
  1380. }
  1381. protected virtual void SetEditorValue(object item, string name, object value)
  1382. {
  1383. try
  1384. {
  1385. CoreUtils.SetPropertyValue(item, name, value);
  1386. }
  1387. catch (Exception e)
  1388. {
  1389. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1390. }
  1391. }
  1392. protected virtual object? GetEditorValue(object item, string name)
  1393. {
  1394. return CoreUtils.GetPropertyValue(item, name);
  1395. }
  1396. protected virtual bool CanCreateItems()
  1397. {
  1398. return true;
  1399. }
  1400. private bool AddEditClick(CoreRow[]? rows)
  1401. {
  1402. if (!IsEnabled || bRefreshing)
  1403. return false;
  1404. if (rows == null || !rows.Any())
  1405. {
  1406. if (!CanCreateItems())
  1407. return false;
  1408. var item = CreateItem();
  1409. if (!AfterCreate(item))
  1410. return false;
  1411. // Yea, and this won't work, because we're actually usually showing the description of a linked item,
  1412. // not the id of the link, and we need to set the ID to have it work properly :-(
  1413. //foreach (String key in VisualFilters.Keys)
  1414. // CoreUtils.SetPropertyValue(item, key, VisualFilters[key]);
  1415. if (EditItems([item]))
  1416. {
  1417. //_CurrentRow = Data.Rows.Count;
  1418. var row = Data.NewRow();
  1419. ObjectToRow(item, row);
  1420. Data.Rows.Add(row);
  1421. InvalidateGrid();
  1422. SelectedRows = [row];
  1423. DoChanged();
  1424. return true;
  1425. }
  1426. return false;
  1427. }
  1428. var items = Array.Empty<T>();
  1429. using (new WaitCursor())
  1430. {
  1431. Stopwatch sw = new Stopwatch();
  1432. sw.Start();
  1433. items = LoadItems(rows);
  1434. //Logger.Send(LogType.Information, "DG:LoadItems", String.Format("Loaded Items: {0}ms", sw.ElapsedMilliseconds));
  1435. sw.Stop();
  1436. }
  1437. if (items.Length != 0)
  1438. {
  1439. var sel = SelectedRows;
  1440. if (EditItems(items))
  1441. {
  1442. for (var i = 0; i < items.Length; i++)
  1443. {
  1444. ObjectToRow(items[i], rows[i]);
  1445. ObjectToRow(items[i], _recordmap[rows[i]]);
  1446. }
  1447. InvalidateGrid();
  1448. SelectedRows = sel;
  1449. DoChanged();
  1450. return true;
  1451. }
  1452. return false;
  1453. }
  1454. return false;
  1455. }
  1456. #endregion
  1457. #region Duplicate
  1458. protected virtual IEnumerable<T> LoadDuplicatorItems(CoreRow[] rows)
  1459. {
  1460. return LoadItems(rows);
  1461. }
  1462. private bool DoDuplicate(Button button, CoreRow[] rows)
  1463. {
  1464. if (!rows.Any())
  1465. {
  1466. MessageBox.Show("Please select at least one record to duplicate!");
  1467. return false;
  1468. }
  1469. /*var ids = ExtractValues(x => x.ID, Selection.Selected).ToArray();
  1470. if (!ids.Any())
  1471. {
  1472. MessageBox.Show("Please select at least one record to duplicate!");
  1473. return false;
  1474. }*/
  1475. var duplicator = (new T() as IDuplicatable)?.GetDuplicator();
  1476. if (duplicator is null)
  1477. {
  1478. MessageBox.Show($"Cannot duplicate {typeof(T)}");
  1479. return false;
  1480. }
  1481. duplicator.Duplicate(LoadDuplicatorItems(rows));// new Filter<T>(x => x.ID).InList(ids));
  1482. return true;
  1483. }
  1484. #endregion
  1485. public virtual T CreateItem()
  1486. {
  1487. var result = new T();
  1488. OnCreateItem?.Invoke(this, result);
  1489. return result;
  1490. }
  1491. public virtual bool AfterCreate(T item)
  1492. {
  1493. return OnAfterCreateItem?.Invoke(this, item) ?? true;
  1494. }
  1495. protected virtual void DoPrint(object sender)
  1496. {
  1497. OnPrintData?.Invoke(sender);
  1498. }
  1499. protected virtual void ShowHelp(string slug)
  1500. {
  1501. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + slug) { UseShellExecute = true });
  1502. }
  1503. protected void ReloadForms<TTargetType, TTargetForm, TSourceForm>(IDynamicEditorForm editor, TTargetType item,
  1504. Expression<Func<TSourceForm, object?>> sourcekey, Guid sourceid)
  1505. where TTargetType : Entity, new()
  1506. where TTargetForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  1507. where TSourceForm : Entity, IRemotable, IPersistent, IDigitalForm<TTargetType>, new()
  1508. {
  1509. var type = typeof(IDynamicOneToManyGrid<,>).MakeGenericType(typeof(TTargetType), typeof(TTargetForm));
  1510. var page =
  1511. editor.Pages?.FirstOrDefault(x => x.GetType().GetInterfaces().Contains(type)) as IDynamicOneToManyGrid<TTargetType, TTargetForm>;
  1512. if (page != null && item != null)
  1513. {
  1514. if (!page.Ready)
  1515. page.Load(item, null);
  1516. CoreTable table;
  1517. if (sourceid == Guid.Empty)
  1518. {
  1519. table = new CoreTable();
  1520. table.LoadColumns(typeof(TSourceForm));
  1521. }
  1522. else
  1523. {
  1524. table = new Client<TSourceForm>().Query(
  1525. new Filter<TSourceForm>(sourcekey).IsEqualTo(sourceid).And(x => x.Form.AppliesTo)
  1526. .IsEqualTo(typeof(TTargetType).EntityName().Split('.').Last())
  1527. );
  1528. }
  1529. var newforms = new List<TTargetForm>();
  1530. foreach (var row in table.Rows)
  1531. {
  1532. var sourceform = row.ToObject<TSourceForm>();
  1533. var targetform = new TTargetForm();
  1534. targetform.Form.ID = sourceform.Form.ID;
  1535. targetform.Form.Synchronise(sourceform.Form);
  1536. newforms.Add(targetform);
  1537. }
  1538. page.Items.Clear();
  1539. page.LoadItems(newforms.ToArray());
  1540. }
  1541. }
  1542. #region ClipBuffer
  1543. private Tuple<ClipAction, CoreRow[]>? ClipBuffer;
  1544. protected void ResetClipBuffer()
  1545. {
  1546. ClipBuffer = null;
  1547. }
  1548. protected void SetClipBuffer(ClipAction action, CoreRow[] rows)
  1549. {
  1550. ClipBuffer = new Tuple<ClipAction, CoreRow[]>(action, rows);
  1551. }
  1552. private void CutToClipBuffer()
  1553. {
  1554. SetClipBuffer(ClipAction.Cut, SelectedRows);
  1555. InvalidateGrid();
  1556. }
  1557. private void CopyToClipBuffer()
  1558. {
  1559. SetClipBuffer(ClipAction.Copy, SelectedRows);
  1560. InvalidateGrid();
  1561. }
  1562. private void PasteFromClipBuffer()
  1563. {
  1564. if (ClipBuffer == null)
  1565. return;
  1566. if (!IsSequenced)
  1567. return;
  1568. using (new WaitCursor())
  1569. {
  1570. var updates = ClipBuffer.Item2.Select(x => x.ToObject<T>()).ToList();
  1571. if (BeforePaste(updates, ClipBuffer.Item1))
  1572. {
  1573. var currow = SelectedRows.FirstOrDefault()
  1574. ?? Data.Rows.LastOrDefault();
  1575. var sequence = currow != null ? currow.Get<T, long>(c => ((ISequenceable)c).Sequence) : 0;
  1576. var postrows = Data.Rows.Where(r => !ClipBuffer.Item2.Contains(r) && r.Get<ISequenceable, long>(x => x.Sequence) >= sequence);
  1577. updates.AddRange(LoadItems(postrows.ToArray()));
  1578. foreach (var update in updates)
  1579. {
  1580. sequence++;
  1581. ((ISequenceable)update).Sequence = sequence;
  1582. }
  1583. }
  1584. if (updates.Any())
  1585. {
  1586. SaveItems(updates.ToArray());
  1587. Refresh(false, true);
  1588. }
  1589. }
  1590. }
  1591. protected virtual bool BeforePaste(IEnumerable<T> items, ClipAction action)
  1592. {
  1593. return true;
  1594. }
  1595. private void Cut_Click(object sender, RoutedEventArgs e)
  1596. {
  1597. CutToClipBuffer();
  1598. }
  1599. private void Copy_Click(object sender, RoutedEventArgs e)
  1600. {
  1601. CopyToClipBuffer();
  1602. }
  1603. private void Paste_Click(object sender, RoutedEventArgs e)
  1604. {
  1605. PasteFromClipBuffer();
  1606. }
  1607. #endregion
  1608. protected virtual void ObjectToRow(T obj, CoreRow row)
  1609. {
  1610. row.Table.FillRow(row, obj);
  1611. }
  1612. #region Import / Export
  1613. protected virtual CoreTable LoadImportKeys(String[] fields)
  1614. {
  1615. var result = new CoreTable();
  1616. result.LoadColumns(new Columns<T>(fields));
  1617. return result;
  1618. }
  1619. protected virtual Guid GetImportID()
  1620. {
  1621. return Guid.Empty;
  1622. }
  1623. protected virtual bool CustomiseImportItem(T item)
  1624. {
  1625. if (IsSequenced)
  1626. ((ISequenceable)item).Sequence = CoreUtils.GenerateSequence();
  1627. return true;
  1628. }
  1629. protected virtual string CustomiseImportFileName(string filename)
  1630. {
  1631. return filename;
  1632. }
  1633. protected virtual void DoImport()
  1634. {
  1635. var list = new DynamicImportList(
  1636. typeof(T),
  1637. GetImportID()
  1638. );
  1639. list.OnImportItem += o => { return CustomiseImportItem((T)o); };
  1640. list.OnCustomiseImport += (o, args) => { args.FileName = CustomiseImportFileName(args.FileName); };
  1641. list.OnSave += (sender, entity) => SaveItem(entity as T);
  1642. list.OnLoad += (sender, type, fields, id) => LoadImportKeys(fields);
  1643. list.ShowDialog();
  1644. Refresh(false, true);
  1645. }
  1646. private void Import_Click(object sender, RoutedEventArgs e)
  1647. {
  1648. DoImport();
  1649. }
  1650. protected virtual void CustomiseExportColumns(List<string> columnnames)
  1651. {
  1652. }
  1653. protected virtual string CustomiseExportFileName(string filename)
  1654. {
  1655. return filename;
  1656. }
  1657. protected virtual void CustomiseExportFilters(Filters<T> filters, CoreRow[] visiblerows)
  1658. {
  1659. }
  1660. protected virtual void ApplyExportFilter(CoreTable table, object data)
  1661. {
  1662. }
  1663. protected virtual void DoExport()
  1664. {
  1665. var columnnames = VisibleColumns.Select(x => x.ColumnName).ToList();
  1666. CustomiseExportColumns(columnnames);
  1667. var form = new DynamicExportForm(typeof(T), columnnames);
  1668. if (form.ShowDialog() != true)
  1669. return;
  1670. var filters = new Filters<T>();
  1671. filters.Add(DefineFilter());
  1672. var predicates = UIComponent.GetFilterPredicates();
  1673. var visiblerows = GetVisibleRows();
  1674. CustomiseExportFilters(filters, visiblerows);
  1675. var columns = new Columns<T>(form.Fields);
  1676. var otherColumns = form.GetChildFields()
  1677. .Select(x => new Tuple<Type, IColumns>(
  1678. x.Key,
  1679. (Activator.CreateInstance(typeof(Columns<>).MakeGenericType(x.Key), new object[] { x.Value }) as IColumns)!))
  1680. .Where(x => x.Item2.ColumnNames().Any()).ToList();
  1681. var reloadColumns = new Columns<T>();
  1682. foreach (var column in columns.ColumnNames())
  1683. {
  1684. reloadColumns.Add(column);
  1685. }
  1686. foreach (var column in HiddenColumns.ColumnNames)
  1687. {
  1688. reloadColumns.Add(column);
  1689. }
  1690. foreach (var (column, _) in predicates)
  1691. {
  1692. reloadColumns.Add(column);
  1693. }
  1694. var sort = LookupFactory.DefineSort<T>();
  1695. Reload(filters, reloadColumns, ref sort, (data, err) => Dispatcher.Invoke(() =>
  1696. {
  1697. if (data is not null)
  1698. {
  1699. var newData = new CoreTable();
  1700. foreach (var column in columns.Items)
  1701. newData.Columns.Add(new CoreColumn { ColumnName = column.Property, DataType = column.Type });
  1702. FilterRows(data, newData, filter: row =>
  1703. {
  1704. foreach(var (_, predicate) in predicates)
  1705. {
  1706. if (!predicate(row))
  1707. {
  1708. return false;
  1709. }
  1710. }
  1711. return true;
  1712. });
  1713. var list = new List<Tuple<Type?, CoreTable>>() { new(typeof(T), newData) };
  1714. list.AddRange(LoadExportTables(filters, otherColumns));
  1715. DoExportTables(list);
  1716. }
  1717. else if (err is not null)
  1718. {
  1719. Logger.Send(LogType.Error, "", $"Error in export: {CoreUtils.FormatException(err)}");
  1720. MessageBox.Show(err.Message);
  1721. }
  1722. }));
  1723. }
  1724. private void Export_Click(object sender, RoutedEventArgs e)
  1725. {
  1726. DoExport();
  1727. }
  1728. /// <summary>
  1729. /// Loads the child tables for an export, based on the filter of the parent table.
  1730. /// </summary>
  1731. /// <remarks>
  1732. /// If not overriden, defaults to creating empty tables with no records.
  1733. /// </remarks>
  1734. /// <param name="filter">Filter for the parent table.</param>
  1735. /// <param name="tableColumns">A list of the child table types, with columns to load for each</param>
  1736. /// <returns>A list of tables, in the same order as they came in <paramref name="tableColumns"/></returns>
  1737. protected virtual IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<T> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  1738. {
  1739. return tableColumns.Select(x =>
  1740. {
  1741. var table = new CoreTable();
  1742. table.LoadColumns(x.Item2);
  1743. return new Tuple<Type?, CoreTable>(x.Item1, table);
  1744. });
  1745. }
  1746. private void DoExportTables(List<Tuple<Type?, CoreTable>> data)
  1747. {
  1748. var filename = CustomiseExportFileName(typeof(T).EntityName().Split('.').Last());
  1749. ExcelExporter.DoExport(data, filename);
  1750. }
  1751. #endregion
  1752. public void ScrollIntoView(CoreRow row)
  1753. {
  1754. UIComponent.ScrollIntoView(row);
  1755. }
  1756. #endregion
  1757. #region Custom Buttons
  1758. private Button CreateButton(BitmapImage? image = null, string? text = null, string? tooltip = null)
  1759. {
  1760. var button = new Button();
  1761. button.SetValue(BorderBrushProperty, new SolidColorBrush(Colors.Gray));
  1762. button.SetValue(BorderThicknessProperty, new Thickness(0.75));
  1763. button.Height = 30;
  1764. UpdateButton(button, image, text, tooltip);
  1765. return button;
  1766. }
  1767. public void UpdateButton(Button button, BitmapImage? image, string? text, string? tooltip = null)
  1768. {
  1769. var stackPnl = new StackPanel();
  1770. stackPnl.Orientation = Orientation.Horizontal;
  1771. //stackPnl.Margin = new Thickness(2);
  1772. if (image != null)
  1773. {
  1774. var img = new Image();
  1775. img.Source = image;
  1776. img.Margin = new Thickness(2);
  1777. img.ToolTip = tooltip;
  1778. stackPnl.Children.Add(img);
  1779. }
  1780. if (!string.IsNullOrEmpty(text))
  1781. {
  1782. button.MaxWidth = double.MaxValue;
  1783. var lbl = new Label();
  1784. lbl.Content = text;
  1785. lbl.VerticalAlignment = VerticalAlignment.Stretch;
  1786. lbl.VerticalContentAlignment = VerticalAlignment.Center;
  1787. lbl.Margin = new Thickness(2, 0, 5, 0);
  1788. lbl.ToolTip = ToolTip;
  1789. stackPnl.Children.Add(lbl);
  1790. }
  1791. else
  1792. button.MaxWidth = 30;
  1793. button.Content = stackPnl;
  1794. button.ToolTip = tooltip;
  1795. }
  1796. private bool bFirstButtonAdded = true;
  1797. private bool AnyButtonsVisible()
  1798. {
  1799. if (Add.Visibility != Visibility.Collapsed)
  1800. return true;
  1801. if (Edit.Visibility != Visibility.Collapsed)
  1802. return true;
  1803. /*if (MultiEdit.Visibility != Visibility.Collapsed)
  1804. return true;*/
  1805. if (Export.Visibility != Visibility.Collapsed)
  1806. return true;
  1807. return false;
  1808. }
  1809. public Button AddButton(string? caption, BitmapImage? image, string? tooltip, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1810. {
  1811. var button = CreateButton(image, caption, tooltip);
  1812. button.Margin = position == DynamicGridButtonPosition.Right
  1813. ? new Thickness(2, 2, 0, 0)
  1814. : bFirstButtonAdded && AnyButtonsVisible()
  1815. ? new Thickness(0, 2, 0, 0)
  1816. : new Thickness(0, 2, 2, 0);
  1817. button.Padding = !String.IsNullOrWhiteSpace(caption) ? new Thickness(5, 1, 5, 1) : new Thickness(1);
  1818. button.Tag = action;
  1819. button.Click += Button_Click;
  1820. if (position == DynamicGridButtonPosition.Right)
  1821. RightButtonStack.Children.Add(button);
  1822. else
  1823. LeftButtonStack.Children.Add(button);
  1824. bFirstButtonAdded = false;
  1825. return button;
  1826. }
  1827. public Button AddButton(string? caption, BitmapImage? image, DynamicGridButtonClickEvent action, DynamicGridButtonPosition position = DynamicGridButtonPosition.Left)
  1828. {
  1829. var result = AddButton(caption, image, null, action, position);
  1830. return result;
  1831. }
  1832. private void Button_Click(object sender, RoutedEventArgs e)
  1833. {
  1834. var button = (Button)sender;
  1835. var action = (DynamicGridButtonClickEvent)button.Tag;
  1836. //CoreRow row = (CurrentRow > -1) && (CurrentRow < Data.Rows.Count) ? Data.Rows[this.CurrentRow] : null;
  1837. if (action.Invoke(button, SelectedRows))
  1838. Refresh(false, true);
  1839. }
  1840. #endregion
  1841. #region Header Actions
  1842. private void SelectColumnsClick()
  1843. {
  1844. var editor = new DynamicGridColumnsEditor(typeof(T));
  1845. editor.DirectEdit = IsDirectEditMode();
  1846. editor.Columns.AddRange(VisibleColumns);
  1847. if (editor.ShowDialog().Equals(true))
  1848. {
  1849. VisibleColumns.Clear();
  1850. VisibleColumns.AddRange(editor.Columns);
  1851. SaveColumns(VisibleColumns);
  1852. //OnSaveColumns?.Invoke(this, editor.Columns);
  1853. Refresh(true, true);
  1854. }
  1855. }
  1856. #endregion
  1857. #region Drag + Drop
  1858. /// <summary>
  1859. /// Handle a number of rows from a different <see cref="DynamicGrid{T}"/> being dragged into this one.
  1860. /// </summary>
  1861. /// <param name="entity">The type of entity that that the rows of <paramref name="table"/> represent.</param>
  1862. /// <param name="table">The data being dragged.</param>
  1863. /// <param name="e"></param>
  1864. protected virtual void OnDragEnd(Type entity, CoreTable table, DragEventArgs e)
  1865. {
  1866. Logger.Send(LogType.Information,"","OnDragEnd");
  1867. }
  1868. /// <summary>
  1869. /// Handle all types of items being dragged onto this grid that aren't handled by <see cref="OnDragEnd(Type, CoreTable, DragEventArgs)"/>,
  1870. /// i.e., data which is not a <see cref="CoreTable"/> from another <see cref="DynamicGrid{T}"/>
  1871. /// </summary>
  1872. /// <remarks>
  1873. /// Can be used to handle files, for example.
  1874. /// </remarks>
  1875. /// <param name="sender"></param>
  1876. /// <param name="e"></param>
  1877. protected virtual void HandleDragDrop(object sender, DragEventArgs e)
  1878. {
  1879. }
  1880. protected virtual void HandleDragOver(object sender, DragEventArgs e)
  1881. {
  1882. }
  1883. protected DragDropEffects DragTable(Type entity, CoreTable table)
  1884. {
  1885. Logger.Send(LogType.Information, "", "DragTable");
  1886. var data = new DataObject();
  1887. data.SetData(DynamicGridUtils.DragFormat, new DynamicGridDragFormat(table.ToDataTable(), entity));
  1888. var effect = DragDrop.DoDragDrop(this, data, DragDropEffects.All);
  1889. return effect;
  1890. }
  1891. protected virtual DragDropEffects OnRowsDragStart(CoreRow[] rows)
  1892. {
  1893. Logger.Send(LogType.Information, "", "OnRowsDragStart");
  1894. var table = new CoreTable();
  1895. table.LoadColumns(Data.Columns);
  1896. table.LoadRows(rows);
  1897. return DragTable(typeof(T), table);
  1898. }
  1899. #endregion
  1900. }