DynamicGrid.cs 85 KB

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