DynamicGrid.cs 44 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438
  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.Runtime.CompilerServices;
  10. using System.Threading.Tasks;
  11. using System.Windows;
  12. using System.Windows.Controls;
  13. using System.Windows.Data;
  14. using System.Windows.Input;
  15. using System.Windows.Media;
  16. using System.Windows.Media.Animation;
  17. using System.Windows.Media.Imaging;
  18. using InABox.Clients;
  19. using InABox.Core;
  20. using InABox.Wpf;
  21. using InABox.WPF;
  22. using Syncfusion.Data;
  23. using Syncfusion.UI.Xaml.Grid;
  24. using Syncfusion.UI.Xaml.Grid.Helpers;
  25. using static InABox.DynamicGrid.IDynamicGrid;
  26. using Color = System.Drawing.Color;
  27. using Columns = InABox.Core.Columns;
  28. using Image = System.Windows.Controls.Image;
  29. using RowColumnIndex = Syncfusion.UI.Xaml.ScrollAxis.RowColumnIndex;
  30. using SolidColorBrush = System.Windows.Media.SolidColorBrush;
  31. using String = System.String;
  32. using VerticalAlignment = System.Windows.VerticalAlignment;
  33. using VirtualizingCellsControl = Syncfusion.UI.Xaml.Grid.VirtualizingCellsControl;
  34. using System.Threading;
  35. using System.Diagnostics.CodeAnalysis;
  36. namespace InABox.DynamicGrid;
  37. public abstract class DynamicGrid<T> : BaseDynamicGrid, IDynamicGridUIComponentParent<T>, IDynamicGrid<T>,
  38. IImportDynamicGrid, IExportDynamicGrid, IDuplicateDynamicGrid, IHelpDynamicGrid
  39. where T : BaseObject, new()
  40. {
  41. #region Events
  42. public ValidateEvent<T>? OnValidate { get; set; }
  43. public event OnDefineFilter? OnDefineFilter;
  44. public event OnCreateItem? OnCreateItem;
  45. public event OnAfterCreateItem? OnAfterCreateItem;
  46. public event EditorValueChangedHandler? OnEditorValueChanged;
  47. public event OnAfterEditorValueChanged? OnAfterEditorValueChangedEvent;
  48. private List<(OnCustomiseEditor, OnCustomiseEditor<T>)> _customiseEditorEvents;
  49. event OnCustomiseEditor? IDynamicGrid.OnCustomiseEditor
  50. {
  51. add
  52. {
  53. if (value is null) return;
  54. void dlg(IDynamicEditorForm sender, T[]? items, DynamicGridColumn column, BaseEditor editor)
  55. {
  56. value?.Invoke(sender, items, column, editor);
  57. }
  58. _customiseEditorEvents ??= new();
  59. _customiseEditorEvents.Add((value, dlg));
  60. OnCustomiseEditor += dlg;
  61. }
  62. remove
  63. {
  64. var (_, dlg) = _customiseEditorEvents.FirstOrDefault(x => x.Item1 == value);
  65. if(dlg is not null)
  66. {
  67. OnCustomiseEditor -= dlg;
  68. }
  69. }
  70. }
  71. public event OnCustomiseEditor<T>? OnCustomiseEditor;
  72. public event EntitySaveEvent? OnBeforeSave;
  73. public event EntitySaveEvent? OnAfterSave;
  74. public delegate void EditorLoaded(IDynamicEditorForm editor, T[] items);
  75. public event EditorLoaded? OnEditorLoaded;
  76. public event OnLoadEditorButtons<T>? OnLoadEditorButtons;
  77. #endregion
  78. protected virtual string HelpSlug()
  79. {
  80. return typeof(T).Name.Split('.').Last().SplitCamelCase().Replace(" ", "_");
  81. }
  82. string IHelpDynamicGrid.HelpSlug() => HelpSlug();
  83. protected override bool CanDuplicate => typeof(T).IsAssignableTo(typeof(IDuplicatable));
  84. public DynamicGrid() : base()
  85. {
  86. }
  87. protected sealed override void PreInit()
  88. {
  89. MasterColumns = new DynamicGridColumns();
  90. MasterColumns.ExtractColumns(typeof(T));
  91. HiddenColumns = new HiddenColumnsList();
  92. if (typeof(T).IsAssignableTo(typeof(ISequenceable)))
  93. {
  94. HiddenColumns.Add(x => (x as ISequenceable)!.Sequence);
  95. }
  96. }
  97. protected override void Init()
  98. {
  99. }
  100. #region IDynamicGridUIComponentParent
  101. protected override IDynamicGridUIComponent CreateUIComponent()
  102. {
  103. return new DynamicGridGridUIComponent<T>
  104. {
  105. Parent = this
  106. };
  107. }
  108. T IDynamicGrid<T>.LoadItem(CoreRow row) => LoadItem(row);
  109. void IDynamicGridUIComponentParent<T>.EntityChanged(T obj, CoreRow row, string changedColumn, Dictionary<string, object?> changes)
  110. => EntityChanged(obj, row, changedColumn, changes);
  111. void IDynamicGridUIComponentParent<T>.UpdateData(T obj, CoreRow row, string changedColumn, Dictionary<CoreColumn, object?> updates)
  112. {
  113. var result = new Dictionary<string, object?>();
  114. foreach (var (col, value) in updates)
  115. {
  116. UpdateRow(row, col.ColumnName, value, refresh: false);
  117. DynamicGridUtils.UpdateEditorValue(new BaseObject[] { obj }, col.ColumnName, value, result);
  118. }
  119. EntityChanged(obj, row, changedColumn, result);
  120. }
  121. #endregion
  122. protected override DynamicGridRowStyleSelector GetRowStyleSelector()
  123. {
  124. return new DynamicGridRowStyleSelector<T, DynamicGridRowStyle>();
  125. }
  126. public DynamicGridColumns MasterColumns { get; protected set; }
  127. public override void OnItemSourceChanged(object value)
  128. {
  129. Data = value as CoreTable;
  130. Refresh(true, true);
  131. }
  132. public class HiddenColumnsList
  133. {
  134. private List<string> Columns { get; set; } = new();
  135. public IEnumerable<string> ColumnNames => Columns;
  136. public void Add(Expression<Func<T, object?>> column) => Add(CoreUtils.GetFullPropertyName(column, "."));
  137. public void Add(IColumn column) => Add(column.Property);
  138. public void Add(string column)
  139. {
  140. if (!Contains(column))
  141. Columns.Add(column);
  142. }
  143. public bool Contains(string column) => Columns.Contains(column);
  144. }
  145. public void AddHiddenColumn(string column) => HiddenColumns.Add(column);
  146. public HiddenColumnsList HiddenColumns { get; private set; }
  147. private static bool IsSequenced => typeof(T).GetInterfaces().Any(x => x.Equals(typeof(ISequenceable)));
  148. #region Options
  149. protected override void DoReconfigure(DynamicGridOptions options)
  150. {
  151. options.ReorderRows = IsSequenced;
  152. }
  153. #endregion
  154. private void EntityChanged(T obj, CoreRow row, string changedColumn, Dictionary<string, object?> changes)
  155. {
  156. OnAfterEditorValueChanged(null, [obj], new AfterEditorValueChangedArgs(changedColumn, changes), changes);
  157. SaveItem(obj);
  158. foreach (var (key, value) in changes)
  159. {
  160. if (row.Table.GetColumnIndex(key) > -1)
  161. row[key] = value;
  162. }
  163. GetUIComponent().UpdateRow(row);
  164. }
  165. #region Column Handling
  166. /// <summary>
  167. /// 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"/>.
  168. /// </summary>
  169. /// <param name="columns"></param>
  170. /// <returns></returns>
  171. protected DynamicGridColumns ExtractColumns(Columns<T> columns)
  172. {
  173. var cols = new DynamicGridColumns();
  174. foreach (var col in columns)
  175. {
  176. var mc = MasterColumns.FirstOrDefault(x => x.ColumnName.Equals(col.Property));
  177. if (mc != null && mc.Editor is not NullEditor && mc.Editor.Visible != Visible.Hidden)
  178. cols.Add(mc);
  179. }
  180. return cols;
  181. }
  182. DynamicGridColumns IDynamicGrid.ExtractColumns(IColumns columns)
  183. {
  184. var cols = new DynamicGridColumns();
  185. foreach (var col in columns)
  186. {
  187. var mc = MasterColumns.FirstOrDefault(x => x.ColumnName.Equals(col.Property));
  188. if (mc != null && mc.Editor is not NullEditor && mc.Editor.Visible != Visible.Hidden)
  189. cols.Add(mc);
  190. }
  191. return cols;
  192. }
  193. public override DynamicGridColumns GenerateColumns()
  194. {
  195. var cols = IsDirectEditMode()
  196. ? new Columns<T>(ColumnTypeFlags.IncludeVisible | ColumnTypeFlags.IncludeForeignKeys)
  197. : new Columns<T>(ColumnTypeFlags.IncludeVisible | ColumnTypeFlags.IncludeLinked);
  198. var columns = ExtractColumns(cols);
  199. OnGenerateColumns?.Invoke(this, new GenerateColumnsEventArgs(columns));
  200. return columns;
  201. }
  202. public event GenerateColumnsEvent? OnGenerateColumns;
  203. public event SaveColumnsEvent? OnSaveColumns;
  204. public event GetAvailableColumnsEvent? GetAvailableColumns;
  205. protected override void SaveColumns(DynamicGridColumns columns)
  206. {
  207. OnSaveColumns?.Invoke(this, new(columns));
  208. }
  209. #endregion
  210. #region Refresh / Reload
  211. protected abstract void Reload(
  212. Filters<T> criteria, Columns<T> columns, ref SortOrder<T>? sort,
  213. CancellationToken token, Action<CoreTable?, Exception?> action);
  214. public Filter<T>? DefineFilter()
  215. {
  216. if (OnDefineFilter is null)
  217. return null;
  218. var result = OnDefineFilter.Invoke(typeof(T)) as Filter<T>;
  219. return result;
  220. }
  221. public IEnumerable<TType> ExtractValues<TType>(Expression<Func<T, TType>> column, Selection selection)
  222. {
  223. var result = selection == Selection.None
  224. ? Enumerable.Empty<TType>()
  225. : selection == Selection.Selected
  226. ? SelectedRows.Select(r => r.Get(column))
  227. : Data.ExtractValues(column);
  228. return result;
  229. }
  230. protected override void ReloadData(CancellationToken token, Action<CoreTable?, Exception?> action)
  231. {
  232. _lookupcache.Clear();
  233. var criteria = new Filters<T>();
  234. var filter = DefineFilter();
  235. if (filter != null)
  236. criteria.Add(filter);
  237. var columns = DataColumns();
  238. var sort = LookupFactory.DefineSort<T>();
  239. if (sort == null && IsSequenced)
  240. sort = new SortOrder<T>("Sequence");
  241. Reload(criteria, columns, ref sort, token, action);
  242. }
  243. public Columns<T> DataColumns()
  244. {
  245. var columns = Columns.None<T>();
  246. foreach (var column in VisibleColumns)
  247. columns.Add(column.ColumnName);
  248. foreach (var column in HiddenColumns.ColumnNames)
  249. columns.Add(new Column<T>(column));
  250. if (!Options.ReadOnly)
  251. {
  252. foreach (var column in LookupFactory.RequiredColumns<T>())
  253. {
  254. columns.Add(column);
  255. }
  256. }
  257. return columns;
  258. }
  259. public void UpdateRow(CoreRow row, T obj, bool invalidateRow = true)
  260. {
  261. ObjectToRow(obj, row);
  262. ObjectToRow(obj, _recordmap[row]);
  263. if (invalidateRow)
  264. {
  265. InvalidateRow(row);
  266. }
  267. }
  268. public void UpdateRows(CoreRow[] rows, T[] objs, bool invalidateRows = true)
  269. {
  270. for(var i = 0; i < objs.Length; ++i)
  271. {
  272. UpdateRow(rows[i], objs[i], invalidateRow: invalidateRows);
  273. }
  274. }
  275. public void AddRow(T data)
  276. {
  277. if (MasterData is null) return;
  278. MasterData.LoadRow(data);
  279. Refresh(false, false);
  280. }
  281. #endregion
  282. #region Item Manipulation
  283. #region Load/Save/Delete
  284. public virtual T[] LoadItems(IList<CoreRow> rows)
  285. {
  286. return rows.ToArray(LoadItem);
  287. }
  288. public abstract T LoadItem(CoreRow row);
  289. public abstract void SaveItem(T item);
  290. public virtual void SaveItems(IEnumerable<T> items)
  291. {
  292. foreach (var item in items)
  293. SaveItem(item);
  294. }
  295. protected virtual bool CanDeleteItems(params CoreRow[] rows)
  296. {
  297. return true;
  298. }
  299. public abstract void DeleteItems(params CoreRow[] rows);
  300. protected override bool CanDeleteRows(params CoreRow[] rows) => CanDeleteItems(rows);
  301. public override void DeleteRows(params CoreRow[] rows) => DeleteItems(rows);
  302. #endregion
  303. #region Edit
  304. protected override void NewRow()
  305. {
  306. CreateItems(null);
  307. }
  308. protected void CreateItems(Func<IEnumerable<T>>? create)
  309. {
  310. var newRows = new List<CoreRow>();
  311. var items = create?.Invoke() ?? CoreUtils.One(CreateItem());
  312. foreach (var item in items)
  313. {
  314. if (!AfterCreate(item))
  315. return;
  316. SaveItem(item);
  317. var datarow = Data.NewRow();
  318. ObjectToRow(item, datarow);
  319. Data.Rows.Add(datarow);
  320. newRows.Add(datarow);
  321. var masterrow = MasterData.NewRow();
  322. ObjectToRow(item, masterrow);
  323. MasterData.Rows.Add(masterrow);
  324. _recordmap[datarow] = masterrow;
  325. }
  326. InvalidateGrid();
  327. SelectedRows = newRows.ToArray();
  328. DoChanged();
  329. }
  330. public virtual DynamicEditorPages LoadEditorPages(T item)
  331. {
  332. DynamicEditorPages pages = new DynamicEditorPages();
  333. DynamicGridUtils.LoadOneToManyPages(typeof(T), pages);
  334. DynamicGridUtils.LoadEnclosedListPages(typeof(T), pages);
  335. DynamicGridUtils.LoadManyToManyPages(typeof(T), pages);
  336. DynamicGridUtils.LoadCustomEditorPages(typeof(T), pages);
  337. pages.RemoveAll(x => !x.Visible);
  338. foreach (var page in pages)
  339. page.Ready = false;
  340. return pages;
  341. }
  342. public virtual void LoadEditorButtons(T item, DynamicEditorButtons buttons)
  343. {
  344. buttons.Clear();
  345. buttons.Add(
  346. "",
  347. Wpf.Resources.help.AsBitmapImage(),
  348. item,
  349. (f, i) =>
  350. {
  351. Process.Start(new ProcessStartInfo("https://prsdigital.com.au/wiki/index.php/" + typeof(T).Name.SplitCamelCase().Replace(" ", "_"))
  352. { UseShellExecute = true });
  353. }
  354. );
  355. OnLoadEditorButtons?.Invoke(item, buttons);
  356. }
  357. protected virtual void BeforeLoad(IDynamicEditorForm form, T[] items)
  358. {
  359. form.BeforeLoad();
  360. }
  361. void IDynamicGrid.InitialiseEditorForm(IDynamicEditorForm editor, object[] items, Func<Type, CoreTable>? pageDataHandler, bool preloadPages)
  362. {
  363. InitialiseEditorForm(editor, items.Cast<T>().ToArray(), pageDataHandler, preloadPages);
  364. }
  365. public virtual bool EditItems(object[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  366. {
  367. var values = items.Cast<T>().ToArray();
  368. return EditItems(values, PageDataHandler, PreloadPages);
  369. }
  370. public virtual void InitialiseEditorForm(IDynamicEditorForm editor, T[] items, Func<Type, CoreTable?>? pageDataHandler = null, bool preloadPages = false)
  371. {
  372. var pages = items.Length == 1 ? LoadEditorPages(items.First()) : new DynamicEditorPages();
  373. var buttons = new DynamicEditorButtons();
  374. if (items.Length == 1)
  375. LoadEditorButtons(items.First(), buttons);
  376. editor.Setup(items.Any() ? items.First().GetType() : typeof(T), pages, buttons, pageDataHandler, preloadPages);
  377. editor.OnCustomiseColumns = (sender, columns) =>
  378. {
  379. columns.Clear();
  380. columns.AddRange(MasterColumns);
  381. };
  382. editor.OnDefineEditor = (o, c) =>
  383. {
  384. var result = GetEditor(o, c);
  385. if (result != null)
  386. result = result.CloneEditor();
  387. return result;
  388. };
  389. editor.OnFormCustomiseEditor += DoCustomiseEditor;
  390. editor.OnDefineFilter = (type, column) => { return DefineLookupFilter(type, column, items); };
  391. //editor.OnDefineFilter += (o, e) => { return DefineFilter(items, e); };
  392. editor.OnDefineLookups = editor => DefineLookups(editor, items);
  393. editor.OnEditorValueChanged += (s, n, v) => EditorValueChanged(editor, items, n, v);
  394. editor.OnAfterEditorValueChanged += (g, args) => AfterEditorValueChanged(g, items, args);
  395. editor.OnReconfigureEditors = g => DoReconfigureEditors(g, items);
  396. editor.OnValidateData += (o, i) => ValidateData(items);
  397. editor.OnSelectPage += SelectPage;
  398. editor.OnSaveItem = (o, e) =>
  399. {
  400. try
  401. {
  402. using var Wait = new WaitCursor();
  403. DoBeforeSave(editor, items);
  404. if (items.Length == 1)
  405. editor.UnloadEditorPages(false);
  406. foreach (var item in items)
  407. SaveItem(item);
  408. if (items.Length == 1)
  409. editor.UnloadEditorPages(true);
  410. DoAfterSave(editor, items);
  411. }
  412. catch (Exception err)
  413. {
  414. MessageBox.Show(err.Message);
  415. e.Cancel = true;
  416. }
  417. };
  418. BeforeLoad(editor, items);
  419. editor.Items = items;
  420. AfterLoad(editor, items);
  421. }
  422. // BaseEditor IDynamicGridUIComponentParent<T>.CustomiseEditor(DynamicGridColumn column, BaseEditor editor)
  423. // {
  424. // var result = editor.CloneEditor();
  425. // CustomiseEditor(new T[] { }, column, result);
  426. // return result;
  427. // }
  428. private void DoCustomiseEditor(IDynamicEditorForm sender, object[] items, DynamicGridColumn column, BaseEditor editor)
  429. {
  430. CustomiseEditor(sender, (T[])items, column, editor);
  431. OnCustomiseEditor?.Invoke(sender, (T[])items, column, editor);
  432. }
  433. protected virtual void CustomiseEditor(IDynamicEditorForm form, T[] items, DynamicGridColumn column, BaseEditor editor)
  434. {
  435. }
  436. protected virtual void DoAfterSave(IDynamicEditorForm editor, T[] items)
  437. {
  438. OnAfterSave?.Invoke(editor, items);
  439. }
  440. protected virtual void DoBeforeSave(IDynamicEditorForm editor, T[] items)
  441. {
  442. OnBeforeSave?.Invoke(editor, items);
  443. }
  444. /// <summary>
  445. /// Edit the <paramref name="items"/> with a non-modal editor window, attaching them to the <paramref name="host"/> provided.
  446. /// </summary>
  447. /// <param name="items">List of objects to edit.</param>
  448. /// <param name="callback">A callback for when the items are finished being edited.</param>
  449. public virtual void EditItemsNonModal(ISubPanelHost host, T[] items, Action<T[], bool> callback, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  450. {
  451. if (!DynamicGridUtils.TryEdit(items, out var editLock))
  452. {
  453. if(editLock.Panel is Window window)
  454. {
  455. Task.Delay(100).ContinueWith(task =>
  456. {
  457. window.WindowState = WindowState.Normal;
  458. window.Activate();
  459. }, TaskScheduler.FromCurrentSynchronizationContext());
  460. }
  461. else
  462. {
  463. 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.");
  464. }
  465. return;
  466. }
  467. DynamicEditorForm editor;
  468. using (var cursor = new WaitCursor())
  469. {
  470. editor = new DynamicEditorForm();
  471. editor.SetValue(Panel.ZIndexProperty, 999);
  472. editor.Form.DisableOKIfUnchanged = true;
  473. InitialiseEditorForm(editor, items, PageDataHandler, PreloadPages);
  474. OnEditorLoaded?.Invoke(editor, items);
  475. }
  476. editLock.Panel = editor;
  477. host.AddSubPanel(editor);
  478. editor.SubPanelClosed += o =>
  479. {
  480. try
  481. {
  482. DynamicGridUtils.FinishEdit(items);
  483. callback(items, editor.Result == true);
  484. }
  485. catch(Exception e)
  486. {
  487. MessageWindow.ShowError("Error occurred while closing editor.", e);
  488. }
  489. };
  490. editor.Show();
  491. }
  492. /// <summary>
  493. /// Edit the <paramref name="items"/> with a modal editor window.
  494. /// </summary>
  495. /// <param name="items">List of objects to edit.</param>
  496. /// <returns><see langword="true"/> if the items were saved.</returns>
  497. public virtual bool EditItems(T[] items, Func<Type, CoreTable?>? PageDataHandler = null, bool PreloadPages = false)
  498. {
  499. DynamicEditorForm editor;
  500. using (var cursor = new WaitCursor())
  501. {
  502. editor = new DynamicEditorForm()
  503. {
  504. WindowStartupLocation = WindowStartupLocation.CenterScreen
  505. };
  506. editor.SetValue(Panel.ZIndexProperty, 999);
  507. InitialiseEditorForm(editor, items, PageDataHandler, PreloadPages);
  508. OnEditorLoaded?.Invoke(editor, items);
  509. }
  510. return editor.ShowDialog() == true;
  511. }
  512. private Dictionary<String, object?> AfterEditorValueChanged(DynamicEditorGrid grid, T[] items, AfterEditorValueChangedArgs args)
  513. {
  514. var changes = new Dictionary<string, object?>();
  515. OnAfterEditorValueChanged(grid, items, args, changes);
  516. OnAfterEditorValueChangedEvent?.Invoke(grid, args);
  517. return changes;
  518. }
  519. protected virtual void OnAfterEditorValueChanged(DynamicEditorGrid? grid, T[] items, AfterEditorValueChangedArgs args, Dictionary<String, object?> changes)
  520. {
  521. }
  522. protected virtual void DoReconfigureEditors(DynamicEditorGrid grid, T[] items)
  523. {
  524. /*if (items.First() is IDimensioned dimensioned)
  525. {
  526. UpdateEditor(grid, x => x.Dimensions.Quantity, dimensioned.Dimensions.GetUnit().HasQuantity);
  527. UpdateEditor(grid, x => x.Dimensions.Length, dimensioned.Dimensions.GetUnit().HasLength);
  528. UpdateEditor(grid, x => x.Dimensions.Width, dimensioned.Dimensions.GetUnit().HasWidth);
  529. UpdateEditor(grid, x => x.Dimensions.Height, dimensioned.Dimensions.GetUnit().HasHeight);
  530. UpdateEditor(grid, x => x.Dimensions.Weight, dimensioned.Dimensions.GetUnit().HasWeight);
  531. }*/
  532. }
  533. private List<string>? ValidateData(T[] items)
  534. {
  535. var errors = new List<string>();
  536. DoValidate(items, errors);
  537. OnValidate?.Invoke(this, items, errors);
  538. return errors.Count != 0 ? errors : null;
  539. }
  540. protected virtual void DoValidate(T[] items, List<string> errors)
  541. {
  542. }
  543. protected virtual void AfterLoad(IDynamicEditorForm editor, T[] items)
  544. {
  545. editor.AfterLoad();
  546. }
  547. protected virtual void SelectPage(object sender, BaseObject[]? items)
  548. {
  549. }
  550. protected virtual Dictionary<string, object?> EditorValueChanged(IDynamicEditorForm editor, T[] items, string name, object value)
  551. {
  552. var result = DynamicGridUtils.UpdateEditorValue(items, name, value);
  553. if (OnEditorValueChanged != null)
  554. {
  555. var newchanges = OnEditorValueChanged(editor, name, value);
  556. foreach (var key in newchanges.Keys)
  557. result[key] = newchanges[key];
  558. }
  559. return result;
  560. }
  561. private readonly Dictionary<Tuple<Type, Type>, Dictionary<object, object>> _lookupcache = new();
  562. protected virtual void DefineLookups(ILookupEditorControl sender, T[] items, bool async = true)
  563. {
  564. if (sender.EditorDefinition is not ILookupEditor editor)
  565. return;
  566. var colname = sender.ColumnName;
  567. if (async)
  568. {
  569. Task.Run(() =>
  570. {
  571. try
  572. {
  573. var values = editor.Values(colname, items);
  574. Dispatcher.Invoke(
  575. () =>
  576. {
  577. try
  578. {
  579. //Logger.Send(LogType.Information, typeof(T).Name, "Dispatching Results" + colname);
  580. sender.LoadLookups(values);
  581. }
  582. catch (Exception e2)
  583. {
  584. Logger.Send(LogType.Information, typeof(T).Name,
  585. "Exception (2) in LoadLookups: " + e2.Message + "\n" + e2.StackTrace);
  586. }
  587. }
  588. );
  589. }
  590. catch (Exception e)
  591. {
  592. Logger.Send(LogType.Information, typeof(T).Name,
  593. "Exception (1) in LoadLookups: " + e.Message + "\n" + e.StackTrace);
  594. }
  595. });
  596. }
  597. else
  598. {
  599. var values = editor.Values(colname, items);
  600. sender.LoadLookups(values);
  601. }
  602. }
  603. /// <summary>
  604. /// Retrieves an editor to display for the given column of <paramref name="item"/>.
  605. /// </summary>
  606. /// <param name="item">The object being edited.</param>
  607. /// <param name="column">The column of the editor.</param>
  608. /// <returns>A new editor, or <see langword="null"/> if no editor defined and no sensible default exists.</returns>
  609. protected virtual BaseEditor? GetEditor(object item, DynamicGridColumn column)
  610. {
  611. return column.Editor ?? DatabaseSchema.Property(item.GetType(), column.ColumnName)?.Editor;
  612. }
  613. protected IFilter? DefineLookupFilter(Type type, string column, T[] items)
  614. {
  615. return LookupFactory.DefineLookupFilter(typeof(T), type, column, items);
  616. }
  617. protected virtual void SetEditorValue(object item, string name, object value)
  618. {
  619. try
  620. {
  621. CoreUtils.SetPropertyValue(item, name, value);
  622. }
  623. catch (Exception e)
  624. {
  625. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  626. }
  627. }
  628. protected virtual object? GetEditorValue(object item, string name)
  629. {
  630. return CoreUtils.GetPropertyValue(item, name);
  631. }
  632. protected override bool CanCreateRows() => CanCreateItems();
  633. protected virtual bool CanCreateItems()
  634. {
  635. return true;
  636. }
  637. protected override bool EditRows(CoreRow[]? rows)
  638. {
  639. if(rows is null)
  640. {
  641. if (!CanCreateItems())
  642. return false;
  643. var item = CreateItem();
  644. if (!AfterCreate(item))
  645. return false;
  646. if(Options.NonModalEditorHost is not null)
  647. {
  648. EditItemsNonModal(Options.NonModalEditorHost, [item], (items, result) =>
  649. {
  650. if (result)
  651. {
  652. var row = Data.NewRow();
  653. ObjectToRow(item, row);
  654. Data.Rows.Add(row);
  655. var masterrow = MasterData.NewRow();
  656. ObjectToRow(item, masterrow);
  657. MasterData.Rows.Add(masterrow);
  658. _recordmap[row] = masterrow;
  659. InvalidateGrid();
  660. SelectedRows = [row];
  661. DoChanged();
  662. }
  663. });
  664. return false;
  665. }
  666. else
  667. {
  668. if (EditItems([item]))
  669. {
  670. //_CurrentRow = Data.Rows.Count;
  671. var row = Data.NewRow();
  672. ObjectToRow(item, row);
  673. Data.Rows.Add(row);
  674. var masterrow = MasterData.NewRow();
  675. ObjectToRow(item, masterrow);
  676. MasterData.Rows.Add(masterrow);
  677. _recordmap[row] = masterrow;
  678. InvalidateGrid();
  679. SelectedRows = [row];
  680. DoChanged();
  681. return true;
  682. }
  683. return false;
  684. }
  685. }
  686. else
  687. {
  688. var items = Array.Empty<T>();
  689. using (new WaitCursor())
  690. {
  691. Stopwatch sw = new Stopwatch();
  692. sw.Start();
  693. items = LoadItems(rows);
  694. //Logger.Send(LogType.Information, "DG:LoadItems", String.Format("Loaded Items: {0}ms", sw.ElapsedMilliseconds));
  695. sw.Stop();
  696. }
  697. if (items.Length != 0)
  698. {
  699. var snaps = items.ToArray(x => x.TakeSnapshot());
  700. if(Options.NonModalEditorHost is not null)
  701. {
  702. EditItemsNonModal(Options.NonModalEditorHost, items, (items, result) =>
  703. {
  704. if (result)
  705. {
  706. var sel = SelectedRows;
  707. UpdateRows(rows, items, invalidateRows: false);
  708. InvalidateGrid();
  709. SelectedRows = sel;
  710. DoChanged();
  711. }
  712. else
  713. {
  714. foreach(var snap in snaps)
  715. {
  716. snap.ResetObject();
  717. }
  718. }
  719. });
  720. return false;
  721. }
  722. else
  723. {
  724. if (EditItems(items))
  725. {
  726. var sel = SelectedRows;
  727. UpdateRows(rows, items, invalidateRows: false);
  728. InvalidateGrid();
  729. SelectedRows = sel;
  730. DoChanged();
  731. return true;
  732. }
  733. else
  734. {
  735. foreach(var snap in snaps)
  736. {
  737. snap.ResetObject();
  738. }
  739. }
  740. }
  741. return false;
  742. }
  743. return false;
  744. }
  745. }
  746. #endregion
  747. #region Duplicate
  748. protected virtual IEnumerable<T> LoadDuplicatorItems(CoreRow[] rows)
  749. {
  750. return LoadItems(rows);
  751. }
  752. bool IDuplicateDynamicGrid.DoDuplicate(CoreRow[] rows) => DoDuplicate(rows);
  753. protected virtual bool DoDuplicate(CoreRow[] rows)
  754. {
  755. if (rows.Length == 0)
  756. {
  757. MessageBox.Show("Please select at least one record to duplicate!");
  758. return false;
  759. }
  760. /*var ids = ExtractValues(x => x.ID, Selection.Selected).ToArray();
  761. if (!ids.Any())
  762. {
  763. MessageBox.Show("Please select at least one record to duplicate!");
  764. return false;
  765. }*/
  766. var duplicator = (new T() as IDuplicatable)?.GetDuplicator();
  767. if (duplicator is null)
  768. {
  769. MessageBox.Show($"Cannot duplicate {typeof(T)}");
  770. return false;
  771. }
  772. duplicator.Duplicate(LoadDuplicatorItems(rows));// new Filter<T>(x => x.ID).InList(ids));
  773. return true;
  774. }
  775. #endregion
  776. public virtual T CreateItem()
  777. {
  778. var result = new T();
  779. OnCreateItem?.Invoke(this, result);
  780. return result;
  781. }
  782. public virtual bool AfterCreate(T item)
  783. {
  784. return OnAfterCreateItem?.Invoke(this, item) ?? true;
  785. }
  786. protected void ReloadForms<TTargetType, TTargetForm, TSourceForm>(IDynamicEditorForm editor, TTargetType item,
  787. Expression<Func<TSourceForm, object?>> sourcekey, Guid sourceid)
  788. where TTargetType : Entity, new()
  789. where TTargetForm : Entity, IRemotable, IPersistent, IDigitalFormInstance, new()
  790. where TSourceForm : Entity, IRemotable, IPersistent, IDigitalForm<TTargetType>, new()
  791. {
  792. var type = typeof(IDynamicOneToManyGrid<,>).MakeGenericType(typeof(TTargetType), typeof(TTargetForm));
  793. var page =
  794. editor.Pages?.FirstOrDefault(x => x.GetType().GetInterfaces().Contains(type)) as IDynamicOneToManyGrid<TTargetType, TTargetForm>;
  795. if (page != null && item != null)
  796. {
  797. if (!page.Ready)
  798. page.Load(item, null);
  799. CoreTable table;
  800. if (sourceid == Guid.Empty)
  801. {
  802. table = new CoreTable();
  803. table.LoadColumns(typeof(TSourceForm));
  804. }
  805. else
  806. {
  807. table = new Client<TSourceForm>().Query(
  808. new Filter<TSourceForm>(sourcekey).IsEqualTo(sourceid).And(x => x.Form.AppliesTo)
  809. .IsEqualTo(typeof(TTargetType).EntityName().Split('.').Last())
  810. );
  811. }
  812. var newforms = new List<TTargetForm>();
  813. foreach (var row in table.Rows)
  814. {
  815. var sourceform = row.ToObject<TSourceForm>();
  816. var targetform = new TTargetForm();
  817. targetform.Form.ID = sourceform.Form.ID;
  818. targetform.Form.Synchronise(sourceform.Form);
  819. newforms.Add(targetform);
  820. }
  821. page.Items.Clear();
  822. page.LoadItems(newforms.ToArray());
  823. }
  824. }
  825. #region ClipBuffer
  826. protected virtual bool BeforeCopy(IList<T> items)
  827. {
  828. return true;
  829. }
  830. protected override void MoveRows(CoreRow[] rows, int index, bool isCopy = false)
  831. {
  832. if (!Options.ReorderRows || !IsSequenced) return;
  833. var items = LoadItems(rows);
  834. if (isCopy)
  835. {
  836. if (!BeforeCopy(items))
  837. {
  838. return;
  839. }
  840. }
  841. var sequence = index < Data.Rows.Count
  842. ? Data.Rows[index].Get<ISequenceable, long>(x => x.Sequence)
  843. : Data.Rows[^1].Get<ISequenceable, long>(x => x.Sequence) + 1;
  844. var postRows = Data.Rows.Where(r => !rows.Contains(r) && r.Get<ISequenceable, long>(x => x.Sequence) >= sequence);
  845. var updates = items.Concatenate(LoadItems(postRows.ToArray()));
  846. foreach (var update in updates)
  847. {
  848. ((ISequenceable)update).Sequence = sequence;
  849. sequence++;
  850. }
  851. if (updates.Length != 0)
  852. {
  853. SaveItems(updates);
  854. DoChanged();
  855. Refresh(false, true);
  856. }
  857. }
  858. #endregion
  859. protected virtual void ObjectToRow(T obj, CoreRow row)
  860. {
  861. row.Table.FillRow(row, obj);
  862. }
  863. #region Import / Export
  864. protected virtual CoreTable LoadImportKeys(String[] fields)
  865. {
  866. var result = new CoreTable();
  867. result.LoadColumns(Columns.None<T>().Add(fields));
  868. return result;
  869. }
  870. protected virtual Guid GetImportID()
  871. {
  872. return Guid.Empty;
  873. }
  874. protected virtual bool CustomiseImportItem(T item)
  875. {
  876. if (IsSequenced)
  877. ((ISequenceable)item).Sequence = CoreUtils.GenerateSequence();
  878. return true;
  879. }
  880. protected virtual string CustomiseImportFileName(string filename)
  881. {
  882. return filename;
  883. }
  884. void IImportDynamicGrid.DoImport() => DoImport();
  885. protected virtual void DoImport()
  886. {
  887. var list = new DynamicImportList(
  888. typeof(T),
  889. GetImportID()
  890. );
  891. list.OnImportItem += o => { return CustomiseImportItem((T)o); };
  892. list.OnCustomiseImport += (o, args) => { args.FileName = CustomiseImportFileName(args.FileName); };
  893. list.OnSave += (sender, entity) => SaveItem(entity as T);
  894. list.OnLoad += (sender, type, fields, id) => LoadImportKeys(fields);
  895. list.ShowDialog();
  896. Refresh(false, true);
  897. }
  898. protected virtual void CustomiseExportColumns(List<string> columnnames)
  899. {
  900. }
  901. protected virtual string CustomiseExportFileName(string filename)
  902. {
  903. return filename;
  904. }
  905. protected virtual void CustomiseExportFilters(Filters<T> filters, CoreRow[] visiblerows)
  906. {
  907. }
  908. protected virtual void ApplyExportFilter(CoreTable table, object data)
  909. {
  910. }
  911. void IExportDynamicGrid.DoExport() => DoExport();
  912. protected virtual void DoExport()
  913. {
  914. var columnnames = VisibleColumns.Select(x => x.ColumnName).ToList();
  915. CustomiseExportColumns(columnnames);
  916. var form = new DynamicExportForm(typeof(T), columnnames);
  917. if (form.ShowDialog() != true)
  918. return;
  919. var filters = new Filters<T>();
  920. filters.Add(DefineFilter());
  921. var predicates = GetUIComponent().GetFilterPredicates();
  922. var visiblerows = GetVisibleRows();
  923. CustomiseExportFilters(filters, visiblerows);
  924. var columns = Columns.None<T>().Add(form.Fields);
  925. var otherColumns = form.GetChildFields()
  926. .Select(x => new Tuple<Type, IColumns>(
  927. x.Key,
  928. Columns.None(x.Key).Add(x.Value)))
  929. .Where(x => x.Item2.ColumnNames().Any()).ToList();
  930. var reloadColumns = Columns.None<T>();
  931. foreach (var column in columns)
  932. {
  933. reloadColumns.Add(column);
  934. }
  935. foreach (var column in HiddenColumns.ColumnNames)
  936. {
  937. reloadColumns.Add(column);
  938. }
  939. foreach (var column in LookupFactory.RequiredColumns<T>())
  940. {
  941. columns.Add(column);
  942. }
  943. foreach (var (column, _) in predicates)
  944. {
  945. reloadColumns.Add(column);
  946. }
  947. CoreTable? data = null;
  948. void LoadExport()
  949. {
  950. var newData = new CoreTable();
  951. newData.LoadColumns(columns);
  952. FilterRows(data.Rows, newData, filter: row =>
  953. {
  954. foreach(var (_, predicate) in predicates)
  955. {
  956. if (!predicate(row))
  957. {
  958. return false;
  959. }
  960. }
  961. return true;
  962. });
  963. var list = new List<Tuple<Type?, CoreTable>>() { new(typeof(T), newData) };
  964. list.AddRange(LoadExportTables(filters, otherColumns));
  965. DoExportTables(list);
  966. }
  967. var sort = LookupFactory.DefineSort<T>();
  968. Reload(filters, reloadColumns, ref sort, CancellationToken.None, (table, err) =>
  969. {
  970. if (table is not null)
  971. {
  972. if (table.Offset == 0 || data is null)
  973. {
  974. data = table;
  975. if (!IsPaging)
  976. {
  977. Dispatcher.Invoke(LoadExport);
  978. }
  979. }
  980. else
  981. {
  982. data.AddPage(table);
  983. if (!IsPaging)
  984. {
  985. Dispatcher.Invoke(LoadExport);
  986. }
  987. }
  988. }
  989. else if (err is not null)
  990. {
  991. Dispatcher.Invoke(() =>
  992. {
  993. MessageWindow.ShowError("Error in export.", err);
  994. });
  995. }
  996. });
  997. }
  998. /// <summary>
  999. /// Loads the child tables for an export, based on the filter of the parent table.
  1000. /// </summary>
  1001. /// <remarks>
  1002. /// If not overriden, defaults to creating empty tables with no records.
  1003. /// </remarks>
  1004. /// <param name="filter">Filter for the parent table.</param>
  1005. /// <param name="tableColumns">A list of the child table types, with columns to load for each</param>
  1006. /// <returns>A list of tables, in the same order as they came in <paramref name="tableColumns"/></returns>
  1007. protected virtual IEnumerable<Tuple<Type?, CoreTable>> LoadExportTables(Filters<T> filter, IEnumerable<Tuple<Type, IColumns>> tableColumns)
  1008. {
  1009. return tableColumns.Select(x =>
  1010. {
  1011. var table = new CoreTable();
  1012. table.LoadColumns(x.Item2);
  1013. return new Tuple<Type?, CoreTable>(x.Item1, table);
  1014. });
  1015. }
  1016. private void DoExportTables(List<Tuple<Type?, CoreTable>> data)
  1017. {
  1018. var filename = CustomiseExportFileName(typeof(T).EntityName().Split('.').Last());
  1019. ExcelExporter.DoExport(data, filename);
  1020. }
  1021. #endregion
  1022. #endregion
  1023. #region Header Actions
  1024. protected override bool SelectColumns([NotNullWhen(true)] out DynamicGridColumns? columns)
  1025. {
  1026. var schema = new DynamicGridObjectColumnSchema(typeof(T));
  1027. var editor = new DynamicGridColumnsEditor(schema, typeof(T)) { WindowStartupLocation = WindowStartupLocation.CenterScreen };
  1028. editor.DirectEdit = IsDirectEditMode();
  1029. editor.Columns.AddRange(VisibleColumns);
  1030. schema.OnProcessColumns += args =>
  1031. {
  1032. GetAvailableColumns?.Invoke(args);
  1033. };
  1034. if (editor.ShowDialog().Equals(true))
  1035. {
  1036. columns = editor.Columns;
  1037. return true;
  1038. }
  1039. else
  1040. {
  1041. columns = null;
  1042. return false;
  1043. }
  1044. }
  1045. #endregion
  1046. #region Drag + Drop
  1047. protected DragDropEffects DragTable(Type entity, CoreTable table)
  1048. {
  1049. Logger.Send(LogType.Information, "", "DragTable");
  1050. var data = new DataObject();
  1051. data.SetData(DynamicGridUtils.DragFormat, new DynamicGridDragFormat(table.ToDataTable(), entity));
  1052. var effect = DragDrop.DoDragDrop(this, data, DragDropEffects.All);
  1053. return effect;
  1054. }
  1055. protected override DragDropEffects OnRowsDragStart(CoreRow[] rows)
  1056. {
  1057. Logger.Send(LogType.Information, "", "OnRowsDragStart");
  1058. var table = new CoreTable();
  1059. table.LoadColumns(Data.Columns);
  1060. table.LoadRows(rows);
  1061. return DragTable(typeof(T), table);
  1062. }
  1063. #endregion
  1064. }
  1065. #region Styling
  1066. public class DynamicGridRowStyle : DynamicGridStyle<VirtualizingCellsControl>
  1067. {
  1068. public DynamicGridRowStyle() : base(null)
  1069. {
  1070. }
  1071. public DynamicGridRowStyle(IDynamicGridStyle source) : base(source)
  1072. {
  1073. }
  1074. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1075. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1076. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1077. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1078. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1079. }
  1080. public class DynamicGridCellStyle : DynamicGridStyle<Control>
  1081. {
  1082. public DynamicGridCellStyle() : base(null)
  1083. {
  1084. }
  1085. public DynamicGridCellStyle(IDynamicGridStyle source) : base(source)
  1086. {
  1087. }
  1088. public override DependencyProperty FontSizeProperty => Control.FontSizeProperty;
  1089. public override DependencyProperty FontStyleProperty => Control.FontStyleProperty;
  1090. public override DependencyProperty FontWeightProperty => Control.FontWeightProperty;
  1091. public override DependencyProperty BackgroundProperty => Control.BackgroundProperty;
  1092. public override DependencyProperty ForegroundProperty => Control.ForegroundProperty;
  1093. }
  1094. // Used to render boolean columns (the default "false" value shows what appears to be an intermediate state, which is ugly
  1095. // This should show nothing for false, and a tick in a box for true
  1096. public class BoolToImageConverter : AbstractConverter<bool, ImageSource?>
  1097. {
  1098. public ImageSource TrueValue { get; set; }
  1099. public ImageSource? FalseValue { get; set; }
  1100. public BoolToImageConverter()
  1101. {
  1102. TrueValue = Wpf.Resources.Bullet_Tick.AsBitmapImage();
  1103. }
  1104. public override ImageSource? Convert(bool value)
  1105. {
  1106. return value ? TrueValue : FalseValue;
  1107. }
  1108. public override bool Deconvert(ImageSource? value)
  1109. {
  1110. return ImageUtils.IsEqual(value as BitmapImage, TrueValue as BitmapImage);
  1111. }
  1112. }
  1113. public class StringToColorImageConverter : IValueConverter
  1114. {
  1115. private readonly int _height = 50;
  1116. private readonly int _width = 25;
  1117. private readonly Dictionary<string, BitmapImage> cache = new();
  1118. public StringToColorImageConverter(int width, int height)
  1119. {
  1120. _width = width;
  1121. _height = height;
  1122. }
  1123. public object? Convert(object value, Type targetType, object parameter, CultureInfo culture)
  1124. {
  1125. var str = value?.ToString();
  1126. if (str is null)
  1127. return null;
  1128. var colorcode = str.TrimStart('#');
  1129. if (!cache.ContainsKey(colorcode))
  1130. {
  1131. var col = ImageUtils.StringToColor(colorcode);
  1132. var bmp = ImageUtils.BitmapFromColor(col, _width, _height, Color.Black);
  1133. cache[colorcode] = bmp.AsBitmapImage();
  1134. }
  1135. var result = cache[colorcode];
  1136. return result;
  1137. }
  1138. public object? ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  1139. {
  1140. return null;
  1141. }
  1142. }
  1143. public class StringArrayConverter : IValueConverter
  1144. {
  1145. object? IValueConverter.Convert(object value, Type targetType, object parameter, CultureInfo culture)
  1146. {
  1147. if (value is string[] strArray)
  1148. {
  1149. return string.Join("\n", strArray);
  1150. }
  1151. Logger.Send(LogType.Error, "", $"Attempt to convert an object which is not a string array: {value}.");
  1152. return null;
  1153. }
  1154. object IValueConverter.ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
  1155. {
  1156. return value;
  1157. }
  1158. }
  1159. #endregion
  1160. [Serializable]
  1161. class DynamicGridDragFormat
  1162. {
  1163. private string entity;
  1164. public DataTable Table { get; set; }
  1165. public Type Entity
  1166. {
  1167. get => CoreUtils.GetEntity(entity);
  1168. [MemberNotNull(nameof(entity))]
  1169. set => entity = value.EntityName();
  1170. }
  1171. public DynamicGridDragFormat(DataTable table, Type entity)
  1172. {
  1173. Table = table;
  1174. Entity = entity;
  1175. }
  1176. }