DynamicGrid.cs 84 KB

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