DynamicGrid.cs 74 KB

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