DynamicGrid.cs 45 KB

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