DynamicFormDesignGrid.cs 82 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Diagnostics;
  4. using System.Diagnostics.CodeAnalysis;
  5. using System.Drawing;
  6. using System.Drawing.Design;
  7. using System.Globalization;
  8. using System.IO;
  9. using System.Linq;
  10. using System.Reflection;
  11. using System.Threading.Tasks;
  12. using System.Windows;
  13. using System.Windows.Controls;
  14. using System.Windows.Controls.Primitives;
  15. using System.Windows.Data;
  16. using System.Windows.Documents;
  17. using System.Windows.Input;
  18. using System.Windows.Markup.Localizer;
  19. using System.Windows.Media;
  20. using System.Windows.Media.Effects;
  21. using System.Windows.Media.Imaging;
  22. using InABox.Clients;
  23. using InABox.Core;
  24. using InABox.WPF;
  25. using Microsoft.CodeAnalysis.CSharp.Syntax;
  26. using Brush = System.Windows.Media.Brush;
  27. using Color = System.Drawing.Color;
  28. using Image = System.Windows.Controls.Image;
  29. using Point = System.Windows.Point;
  30. using Rectangle = System.Windows.Shapes.Rectangle;
  31. namespace InABox.DynamicGrid
  32. {
  33. public class DynamicFormCreateElementArgs : EventArgs
  34. {
  35. public DynamicFormCreateElementArgs(DFLayoutElement element, string name)
  36. {
  37. Element = element;
  38. Name = name;
  39. }
  40. public DFLayoutElement Element { get; }
  41. public string Name { get; }
  42. }
  43. public delegate FrameworkElement DynamicFormCreateElementDelegate(object sender, DynamicFormCreateElementArgs e);
  44. public delegate void DynamicFormAfterDesignDelegate(object sender);
  45. public delegate void DynamicFormAfterRenderDelegate(DynamicFormDesignGrid sender);
  46. public delegate void DynamicFormOnChangedDelegate(DynamicFormDesignGrid sender, string fieldName);
  47. public enum FormMode
  48. {
  49. /// <summary>
  50. /// The form is read-only.
  51. /// </summary>
  52. ReadOnly,
  53. /// <summary>
  54. /// Standard option for when the form is being filled in by the associated employee.
  55. /// </summary>
  56. Filling,
  57. /// <summary>
  58. /// Standard option for when the form is being previewed - that is, it is acting with placeholder values that will not get saved.
  59. /// It is still editable.
  60. /// </summary>
  61. Preview,
  62. /// <summary>
  63. /// Once the form has been completed, or the person editing is not the employee the form applies to, then they are put in Editing Mode.<br/>
  64. /// This is only possible if <see cref="CanEditCompletedForms"/> is enabled.
  65. /// </summary>
  66. Editing,
  67. /// <summary>
  68. /// The form layout is being designed
  69. /// </summary>
  70. Designing
  71. }
  72. public class DynamicFormDesignGrid : Grid, IDFRenderer
  73. {
  74. //private bool _designing;
  75. public bool GridInitialized { get; private set; } = false;
  76. //private bool _readonly;
  77. private readonly SolidColorBrush BackgroundBrush = new(Colors.WhiteSmoke);
  78. private readonly SolidColorBrush BorderBrush = new(Colors.Silver);
  79. private readonly Dictionary<Type, IDynamicGrid> elementgrids = new();
  80. private readonly Dictionary<DFLayoutControl, FrameworkElement> elementmap = new();
  81. private readonly Dictionary<DFLayoutControl, Border> borderMap = new();
  82. private readonly SolidColorBrush FieldBrush = new(Colors.LightYellow);
  83. private readonly SolidColorBrush RequiredFieldBrush = new(Colors.Orange);
  84. public DynamicFormDesignGrid()
  85. {
  86. PreviewMouseLeftButtonDown += Grid_PreviewMouseLeftButtonDown;
  87. PreviewMouseMove += Grid_PreviewMouseMove;
  88. PreviewMouseLeftButtonUp += Grid_PreviewMouseLeftButtonUp;
  89. }
  90. #region Backing Properties
  91. private readonly List<DynamicFormElement> _elements = new();
  92. private readonly List<DynamicFormElementAction> _elementActions = new();
  93. private bool _showBorders = true;
  94. private IDigitalFormDataModel? _datamodel;
  95. private DFLayout form = new();
  96. private FormMode _mode;
  97. private IList<DigitalFormVariable> _variables = new List<DigitalFormVariable>();
  98. private bool _isChanged;
  99. private bool _changing = false;
  100. #endregion
  101. #region Public Properties
  102. public bool ShowBorders
  103. {
  104. get => _showBorders || _mode == FormMode.Designing;
  105. set
  106. {
  107. _showBorders = value;
  108. CheckRefresh();
  109. }
  110. }
  111. public IDigitalFormDataModel? DataModel
  112. {
  113. get => _datamodel;
  114. set
  115. {
  116. _datamodel = value;
  117. if(_datamodel != null)
  118. {
  119. var task = Task.Run(() =>
  120. {
  121. var waiting = true;
  122. _datamodel.Load(m => { waiting = false; });
  123. while (waiting) ;
  124. });
  125. task.Wait();
  126. }
  127. CheckRefresh();
  128. }
  129. }
  130. public DFLayout Form
  131. {
  132. get => form;
  133. set
  134. {
  135. form = value;
  136. form.Renderer = this;
  137. CheckRefresh();
  138. }
  139. }
  140. public FormMode Mode
  141. {
  142. get => _mode;
  143. set
  144. {
  145. if (_mode != value)
  146. {
  147. var oldMode = _mode;
  148. if (_mode == FormMode.Designing)
  149. {
  150. OnAfterDesign?.Invoke(this);
  151. }
  152. _mode = value;
  153. CheckRefresh(oldMode != FormMode.Designing);
  154. }
  155. }
  156. }
  157. public bool IsDesigning { get => _mode == FormMode.Designing; }
  158. public bool IsReadOnly { get => _mode == FormMode.ReadOnly; }
  159. public bool IsEditing { get => _mode == FormMode.Editing || _mode == FormMode.Filling; }
  160. public bool IsChanged => _isChanged;
  161. public delegate DigitalFormVariable? CreateVariableHandler(Type fieldType);
  162. public delegate bool EditVariableHandler(DigitalFormVariable variable);
  163. public event CreateVariableHandler? OnCreateVariable;
  164. public event EditVariableHandler? OnEditVariable;
  165. public delegate void CustomiseElementContextMenuHandler(ContextMenu menu, DFLayoutElement element);
  166. public event CustomiseElementContextMenuHandler? CustomiseElementContextMenu;
  167. public IList<DigitalFormVariable> Variables
  168. {
  169. get => _variables;
  170. set
  171. {
  172. _variables = value;
  173. CheckRefresh();
  174. }
  175. }
  176. #endregion
  177. #region Events
  178. public event DynamicFormAfterDesignDelegate? OnAfterDesign;
  179. public event DynamicFormCreateElementDelegate? OnCreateElement;
  180. public event DynamicFormAfterRenderDelegate? OnAfterRender;
  181. public event DynamicFormOnChangedDelegate? OnChanged;
  182. #endregion
  183. #region Rows
  184. class RowData
  185. {
  186. public string RowHeight { get; set; }
  187. public RowData(string rowHeight)
  188. {
  189. RowHeight = rowHeight;
  190. }
  191. }
  192. internal void CollapseRows(FormHeader header, bool collapsed)
  193. {
  194. var startRow = this.GetRow(header) + this.GetRowSpan(header);
  195. var nextRow = elementmap
  196. .Where(x => x.Value is DFHeaderControl headerControl && headerControl.Header != header)
  197. .Select(x => this.GetRow(x.Value))
  198. .Where(x => x >= startRow).DefaultIfEmpty(-1).Min();
  199. if (nextRow == -1)
  200. {
  201. nextRow = RowDefinitions.Count;
  202. }
  203. for (int row = startRow; row < nextRow; ++row)
  204. {
  205. var rowDefinition = RowDefinitions[row];
  206. if(rowDefinition.Tag is not RowData rowData)
  207. {
  208. throw new Exception("Row definition tag is not RowData");
  209. }
  210. if (collapsed)
  211. {
  212. rowDefinition.Height = new GridLength(0);
  213. }
  214. else
  215. {
  216. rowDefinition.Height = StringToGridLength(rowData.RowHeight);
  217. }
  218. }
  219. }
  220. #endregion
  221. #region Elements
  222. class DynamicFormElement
  223. {
  224. public string Caption { get; set; }
  225. public Type ElementType { get; set; }
  226. public string Category { get; set; }
  227. public bool AllowDuplicate { get; set; }
  228. public object? Tag { get; set; }
  229. public Func<object?, DFLayoutElement>? CreateElement { get; set; }
  230. public bool Visible { get; set; }
  231. public DynamicFormElement(string caption, Type elementType, string category, bool allowDuplicate, bool visible, object? tag, Func<object?, DFLayoutElement>? createElement)
  232. {
  233. Caption = caption;
  234. ElementType = elementType;
  235. Category = category;
  236. AllowDuplicate = allowDuplicate;
  237. Tag = tag;
  238. CreateElement = createElement;
  239. Visible = visible;
  240. }
  241. }
  242. class DynamicFormElementAction
  243. {
  244. public string Caption { get; set; }
  245. public Bitmap? Image { get; set; }
  246. public string Category { get; set; }
  247. public object? Tag { get; set; }
  248. public Func<object?, DFLayoutElement?> OnClick { get; set; }
  249. public DynamicFormElementAction(string caption, Bitmap? image, string category, object? tag, Func<object?, DFLayoutElement> onClick)
  250. {
  251. Caption = caption;
  252. Image = image;
  253. Category = category;
  254. Tag = tag;
  255. OnClick = onClick;
  256. }
  257. }
  258. public void ClearElementTypesAndActions()
  259. {
  260. _elements.Clear();
  261. _elementActions.Clear();
  262. }
  263. public void AddElementType<TElement>(string caption, string category, bool allowduplicate = false, bool visible = true)
  264. where TElement : DFLayoutElement
  265. {
  266. AddElementType(typeof(TElement), caption, category, allowduplicate, visible: visible);
  267. }
  268. public void AddElementType<TElement, TTag>(string caption, string category, TTag tag, Func<TTag, TElement> createElement, bool allowduplicate = false, bool visible = true)
  269. where TElement : DFLayoutElement
  270. {
  271. AddElementType(typeof(TElement), caption, category, tag, createElement, allowduplicate, visible: visible);
  272. }
  273. public void AddElementType(Type TElement, string caption, string category, bool allowduplicate = false, bool visible = true)
  274. {
  275. _elements.Add(new DynamicFormElement(caption, TElement, category, allowduplicate, visible, null, null));
  276. }
  277. public void AddElementType<TTag>(Type TElement, string caption, string category, TTag tag, Func<TTag, DFLayoutElement> createElement, bool allowduplicate = false, bool visible = true)
  278. {
  279. _elements.Add(new DynamicFormElement(caption, TElement, category, allowduplicate, visible, tag, x => createElement((TTag)x)));
  280. }
  281. public void AddElementAction<TTag>(string caption, Bitmap? image, string category, TTag tag, Func<TTag, DFLayoutElement?> onClick)
  282. {
  283. _elementActions.Add(new(caption, image, category, tag, x => onClick((TTag)x)));
  284. }
  285. internal FrameworkElement? CreateElement(DFLayoutElement element)
  286. {
  287. var elementType = element.GetType();
  288. if(_elements.FirstOrDefault(x => x.ElementType == elementType) is DynamicFormElement el)
  289. {
  290. return OnCreateElement?.Invoke(this, new DynamicFormCreateElementArgs(element, el.Caption));
  291. }
  292. return null;
  293. }
  294. #endregion
  295. #region Utilities
  296. private static VerticalAlignment GetVerticalAlignment(DFLayoutAlignment alignment)
  297. {
  298. return alignment == DFLayoutAlignment.Start
  299. ? VerticalAlignment.Top
  300. : alignment == DFLayoutAlignment.End
  301. ? VerticalAlignment.Bottom
  302. : alignment == DFLayoutAlignment.Middle
  303. ? VerticalAlignment.Center
  304. : VerticalAlignment.Stretch;
  305. }
  306. private static HorizontalAlignment GetHorizontalAlignment(DFLayoutAlignment alignment)
  307. {
  308. return alignment == DFLayoutAlignment.Start
  309. ? HorizontalAlignment.Left
  310. : alignment == DFLayoutAlignment.End
  311. ? HorizontalAlignment.Right
  312. : alignment == DFLayoutAlignment.Middle
  313. ? HorizontalAlignment.Center
  314. : HorizontalAlignment.Stretch;
  315. }
  316. private static GridLength StringToGridLength(string length)
  317. {
  318. if (string.IsNullOrWhiteSpace(length) || string.Equals(length.ToUpper(), "AUTO"))
  319. return new GridLength(1, GridUnitType.Auto);
  320. if (!double.TryParse(length.Replace("*", ""), out var value))
  321. value = 1.0F;
  322. var type = length.Contains('*') ? GridUnitType.Star : GridUnitType.Pixel;
  323. return new GridLength(value, type);
  324. }
  325. private static string GridLengthToString(GridLength length)
  326. {
  327. if (length.IsStar)
  328. return length.Value == 1.0F ? "*" : string.Format("{0}*", length.Value);
  329. if (length.IsAuto)
  330. return "Auto";
  331. return length.Value.ToString();
  332. }
  333. private static string FormatGridLength(GridLength length, IEnumerable<GridLength> others)
  334. {
  335. if (length.IsStar)
  336. {
  337. double total = 0.0F;
  338. foreach (var other in others.Where(x => x.IsStar))
  339. total += other.Value;
  340. return string.Format("{0:F0}%", total != 0 ? length.Value * 100.0F / total : 0);
  341. }
  342. if (length.IsAuto)
  343. return "Auto";
  344. return string.Format("{0}px", length.Value);
  345. }
  346. private static void AddClick<TTag>(ButtonBase button, TTag tag, Action<TTag> click)
  347. {
  348. button.Tag = tag;
  349. button.Click += (o, e) => click((TTag)(o as FrameworkElement)!.Tag);
  350. }
  351. #endregion
  352. #region Design Mode
  353. #region Selection
  354. private class CellSelection : Border
  355. {
  356. private static readonly System.Windows.Media.Color MainSelectionBorder = Colors.LightBlue;
  357. private int startRow;
  358. private int endRow;
  359. private int startColumn;
  360. private int endColumn;
  361. public int StartRow
  362. {
  363. get => startRow;
  364. set
  365. {
  366. startRow = value;
  367. UpdatePosition();
  368. }
  369. }
  370. public int StartColumn
  371. {
  372. get => startColumn;
  373. set
  374. {
  375. startColumn = value;
  376. UpdatePosition();
  377. }
  378. }
  379. public int EndRow
  380. {
  381. get => endRow;
  382. set
  383. {
  384. endRow = value;
  385. UpdatePosition();
  386. }
  387. }
  388. public int EndColumn
  389. {
  390. get => endColumn;
  391. set
  392. {
  393. endColumn = value;
  394. UpdatePosition();
  395. }
  396. }
  397. public bool Selecting = true;
  398. public enum SelectionTypes
  399. {
  400. Main,
  401. Secondary,
  402. Resizable,
  403. ResizeBackground
  404. }
  405. public SelectionTypes SelectionType;
  406. public enum Direction
  407. {
  408. None,
  409. Left,
  410. Right,
  411. Top,
  412. Bottom,
  413. All
  414. }
  415. public Direction DragDirection;
  416. public bool IsDragging => DragDirection != Direction.None;
  417. public bool IsRowSelection => StartColumn == 0;
  418. public bool IsColumnSelection => StartRow == 0;
  419. public CellSelection(int startRow, int startColumn, int endRow, int endColumn, SelectionTypes selectionType)
  420. {
  421. SelectionType = selectionType;
  422. switch (selectionType)
  423. {
  424. case SelectionTypes.Main:
  425. InitialiseMain();
  426. break;
  427. case SelectionTypes.Secondary:
  428. InitialiseSecondary();
  429. break;
  430. case SelectionTypes.Resizable:
  431. InitializeResizable();
  432. break;
  433. case SelectionTypes.ResizeBackground:
  434. InitializeResizeBackground();
  435. break;
  436. }
  437. this.startRow = startRow;
  438. this.startColumn = startColumn;
  439. this.endRow = endRow;
  440. this.endColumn = endColumn;
  441. UpdatePosition();
  442. }
  443. private void InitialiseMain()
  444. {
  445. var colour = MainSelectionBorder;
  446. BorderBrush = new SolidColorBrush(colour);
  447. Background = new SolidColorBrush(new System.Windows.Media.Color
  448. {
  449. A = (byte)(colour.A / 2),
  450. R = colour.R,
  451. G = colour.G,
  452. B = colour.B
  453. });
  454. SetZIndex(this, 2);
  455. BorderThickness = new Thickness(1);
  456. }
  457. private void InitialiseSecondary()
  458. {
  459. var rectangle = new Rectangle
  460. {
  461. StrokeDashArray = new DoubleCollection { 4, 4 },
  462. Stroke = new SolidColorBrush(Colors.Gray),
  463. StrokeThickness = 1.5
  464. };
  465. rectangle.SetBinding(Rectangle.WidthProperty, new Binding("ActualWidth") { Source = this });
  466. rectangle.SetBinding(Rectangle.HeightProperty, new Binding("ActualHeight") { Source = this });
  467. var brush = new VisualBrush { Visual = rectangle };
  468. BorderBrush = brush;
  469. BorderThickness = new Thickness(1.5);
  470. Margin = new Thickness(3);
  471. }
  472. private void InitializeResizable()
  473. {
  474. var rectangle = new Rectangle
  475. {
  476. StrokeDashArray = new DoubleCollection { 4, 4 },
  477. Stroke = new SolidColorBrush(Colors.Gray),
  478. StrokeThickness = 3
  479. };
  480. rectangle.SetBinding(Rectangle.WidthProperty, new Binding("ActualWidth") { Source = this });
  481. rectangle.SetBinding(Rectangle.HeightProperty, new Binding("ActualHeight") { Source = this });
  482. var brush = new VisualBrush { Visual = rectangle };
  483. BorderBrush = brush;
  484. Background = new SolidColorBrush(Colors.Transparent);
  485. SetZIndex(this, 2);
  486. BorderThickness = new Thickness(10);
  487. MouseMove += Resizable_MouseMove;
  488. }
  489. private void InitializeResizeBackground()
  490. {
  491. var colour = Colors.WhiteSmoke;
  492. Background = new SolidColorBrush(new System.Windows.Media.Color
  493. {
  494. A = (byte)(colour.A / 2),
  495. R = colour.R,
  496. G = colour.G,
  497. B = colour.B
  498. });
  499. SetZIndex(this, 1);
  500. BorderThickness = new Thickness(0);
  501. }
  502. public bool StartDragging(Point position)
  503. {
  504. if (!IsMouseDirectlyOver) return false;
  505. var dX = Math.Min(position.X, ActualWidth - position.X);
  506. var dY = Math.Min(position.Y, ActualHeight - position.Y);
  507. if(Math.Min(dX, dY) < 10)
  508. {
  509. if (dX < dY)
  510. {
  511. DragDirection = position.X < ActualWidth / 2 ? Direction.Left : Direction.Right;
  512. }
  513. else
  514. {
  515. DragDirection = position.Y < ActualHeight / 2 ? Direction.Top : Direction.Bottom;
  516. }
  517. }
  518. else
  519. {
  520. DragDirection = Direction.All;
  521. return false;
  522. }
  523. return true;
  524. }
  525. private void Resizable_MouseMove(object sender, MouseEventArgs e)
  526. {
  527. if (!IsMouseDirectlyOver || IsDragging) return;
  528. var position = e.GetPosition(this);
  529. var dX = Math.Min(position.X, ActualWidth - position.X);
  530. var dY = Math.Min(position.Y, ActualHeight - position.Y);
  531. if (Math.Min(dX, dY) < 10)
  532. {
  533. if (dX < dY)
  534. {
  535. Cursor = Cursors.SizeWE;
  536. }
  537. else
  538. {
  539. Cursor = Cursors.SizeNS;
  540. }
  541. }
  542. else
  543. {
  544. Cursor = Cursors.Arrow;
  545. }
  546. }
  547. public void SetEnd(int endRow, int endColumn)
  548. {
  549. this.endRow = endRow;
  550. this.endColumn = endColumn;
  551. UpdatePosition();
  552. }
  553. public void SetSize(int startRow, int startColumn, int endRow, int endColumn)
  554. {
  555. this.startRow = startRow;
  556. this.startColumn = startColumn;
  557. this.endRow = endRow;
  558. this.endColumn = endColumn;
  559. UpdatePosition();
  560. }
  561. private void UpdatePosition()
  562. {
  563. Grid.SetRow(this, Math.Min(startRow, endRow));
  564. Grid.SetRowSpan(this, Math.Abs(endRow - startRow) + 1);
  565. Grid.SetColumn(this, Math.Min(startColumn, endColumn));
  566. Grid.SetColumnSpan(this, Math.Abs(endColumn - startColumn) + 1);
  567. }
  568. public CellRange ToRange() => new CellRange(StartRow, StartColumn, EndRow, EndColumn);
  569. }
  570. private CellSelection? Selection;
  571. private Dictionary<DFLayoutControl, CellSelection> SelectedItemsSelections = new();
  572. private class Range
  573. {
  574. public int Start { get; set; }
  575. public int End { get; set; }
  576. public int Min => Math.Min(Start, End);
  577. public int Max => Math.Max(Start, End);
  578. public Range(int start, int end)
  579. {
  580. Start = start;
  581. End = end;
  582. }
  583. public override string ToString() => $"{Start} -> {End}";
  584. }
  585. private class CellRange
  586. {
  587. public int StartRow { get; set; }
  588. public int StartColumn { get; set; }
  589. public int EndRow { get; set; }
  590. public int EndColumn { get; set; }
  591. public int MinRow => Math.Min(StartRow, EndRow);
  592. public int MinColumn => Math.Min(StartColumn, EndColumn);
  593. public int MaxRow => Math.Max(StartRow, EndRow);
  594. public int MaxColumn => Math.Max(StartColumn, EndColumn);
  595. public int RowSpan => Math.Abs(EndRow - StartRow) + 1;
  596. public int ColumnSpan => Math.Abs(EndColumn - StartColumn) + 1;
  597. public CellRange(int row, int column)
  598. {
  599. StartRow = row;
  600. EndRow = row;
  601. StartColumn = column;
  602. EndColumn = column;
  603. }
  604. public CellRange(int startRow, int startColumn, int endRow, int endColumn)
  605. {
  606. StartRow = startRow;
  607. EndRow = endRow;
  608. StartColumn = startColumn;
  609. EndColumn = endColumn;
  610. }
  611. public override string ToString() => $"({StartColumn}, {StartRow}) -> ({EndColumn}, {EndRow})";
  612. }
  613. private void ClearSelection()
  614. {
  615. if (Selection is null) return;
  616. Children.Remove(Selection);
  617. Selection = null;
  618. UpdateSecondarySelection();
  619. }
  620. private void StartSelection(int row, int column)
  621. {
  622. if (Selection is not null) ClearSelection();
  623. Selection = new CellSelection(row, column, row, column, CellSelection.SelectionTypes.Main);
  624. Selection.MouseRightButtonDown += Selection_MouseRightButtonDown;
  625. Children.Add(Selection);
  626. UpdateSecondarySelection();
  627. }
  628. private void StartRowSelection(int row)
  629. {
  630. if (Selection is not null) ClearSelection();
  631. Selection = new CellSelection(row, 0, row, ColumnDefinitions.Count - 1, CellSelection.SelectionTypes.Main);
  632. Selection.MouseRightButtonDown += Selection_MouseRightButtonDown;
  633. Children.Add(Selection);
  634. UpdateSecondarySelection();
  635. }
  636. private void StartColumnSelection(int column)
  637. {
  638. if (Selection is not null) ClearSelection();
  639. Selection = new CellSelection(0, column, RowDefinitions.Count - 1, column, CellSelection.SelectionTypes.Main);
  640. Selection.MouseRightButtonDown += Selection_MouseRightButtonDown;
  641. Children.Add(Selection);
  642. UpdateSecondarySelection();
  643. }
  644. private Tuple<int, int> GetRowColIndex(Point point)
  645. {
  646. int rowIdx = -1;
  647. int colIdx = -1;
  648. for(var c = 0; c < ColumnDefinitions.Count; ++c)
  649. {
  650. var column = ColumnDefinitions[c];
  651. if(point.X >= column.Offset && point.X < column.Offset + column.ActualWidth)
  652. {
  653. colIdx = c;
  654. break;
  655. }
  656. }
  657. for(var r = 0; r < RowDefinitions.Count; ++r)
  658. {
  659. var row = RowDefinitions[r];
  660. if(point.Y >= row.Offset && point.Y < row.Offset + row.ActualHeight)
  661. {
  662. rowIdx = r;
  663. break;
  664. }
  665. }
  666. return new Tuple<int, int>(rowIdx, colIdx);
  667. }
  668. private void UpdateSecondarySelection()
  669. {
  670. List<DFLayoutControl> items;
  671. if (Selection is null || Selection.IsRowSelection || Selection.IsColumnSelection)
  672. {
  673. items = new List<DFLayoutControl>();
  674. }
  675. else
  676. {
  677. items = GetSelectedItems().ToList();
  678. }
  679. var removes = new List<DFLayoutControl>();
  680. foreach(var (control, selection) in SelectedItemsSelections)
  681. {
  682. if (!items.Contains(control))
  683. {
  684. removes.Add(control);
  685. Children.Remove(selection);
  686. }
  687. }
  688. foreach(var remove in removes)
  689. {
  690. SelectedItemsSelections.Remove(remove);
  691. }
  692. foreach(var item in items)
  693. {
  694. if (!SelectedItemsSelections.ContainsKey(item))
  695. {
  696. var selection = new CellSelection(
  697. item.Row, item.Column,
  698. item.Row + item.RowSpan - 1, item.Column + item.ColumnSpan - 1,
  699. CellSelection.SelectionTypes.Secondary);
  700. SelectedItemsSelections.Add(item, selection);
  701. Children.Add(selection);
  702. }
  703. }
  704. }
  705. private void ContinueSelection(int row, int column)
  706. {
  707. if (Selection is null) return;
  708. row = Math.Max(row, 1);
  709. column = Math.Max(column, 1);
  710. Selection.Selecting = true;
  711. if (Selection.IsRowSelection)
  712. {
  713. Selection.EndRow = row;
  714. }
  715. else if (Selection.IsColumnSelection)
  716. {
  717. Selection.EndColumn = column;
  718. }
  719. else
  720. {
  721. Selection.SetEnd(row, column);
  722. }
  723. UpdateSecondarySelection();
  724. }
  725. private void Grid_PreviewMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  726. {
  727. if (!IsDesigning) return;
  728. if(Resizer is not null)
  729. {
  730. if (Resizer.StartDragging(e.GetPosition(Resizer)))
  731. {
  732. Cursor = Resizer.DragDirection switch
  733. {
  734. CellSelection.Direction.All => Cursors.SizeAll,
  735. CellSelection.Direction.Left or CellSelection.Direction.Right => Cursors.SizeWE,
  736. _ => Cursors.SizeNS
  737. };
  738. if(Resizer.DragDirection == CellSelection.Direction.All)
  739. {
  740. StartDragPosition = GetRowColIndex(e.GetPosition(this));
  741. }
  742. }
  743. return;
  744. }
  745. var (row, column) = GetRowColIndex(e.GetPosition(this));
  746. if(Selection is not null && (Keyboard.IsKeyDown(Key.LeftShift) || Keyboard.IsKeyDown(Key.RightShift)))
  747. {
  748. ContinueSelection(row, column);
  749. }
  750. else if(Selection is not null && Selection.Selecting)
  751. {
  752. Selection.Selecting = false;
  753. }
  754. else
  755. {
  756. if (column == 0)
  757. {
  758. if (row == 0) return;
  759. StartRowSelection(row);
  760. }
  761. else if (row == 0)
  762. {
  763. if (column == 0) return;
  764. StartColumnSelection(column);
  765. }
  766. else
  767. {
  768. StartSelection(row, column);
  769. }
  770. }
  771. }
  772. private void Grid_PreviewMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
  773. {
  774. if (!IsDesigning) return;
  775. var (row, column) = GetRowColIndex(e.GetPosition(this));
  776. if (Resizer is not null)
  777. {
  778. ResizeMouseMove(sender, e);
  779. return;
  780. }
  781. if (Selection is null || !Selection.Selecting) return;
  782. ContinueSelection(row, column);
  783. }
  784. private void Grid_PreviewMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
  785. {
  786. if(Resizer is not null)
  787. {
  788. Resizer.DragDirection = CellSelection.Direction.None;
  789. Cursor = Cursors.Arrow;
  790. }
  791. else if (Selection is not null)
  792. {
  793. Selection.Selecting = false;
  794. }
  795. }
  796. private IEnumerable<Tuple<DFLayoutControl, FrameworkElement>> GetSelectedMaps(CellRange? range = null)
  797. {
  798. range ??= Selection?.ToRange();
  799. if (range is null) yield break;
  800. var minRow = Math.Min(range.StartRow, range.EndRow);
  801. var maxRow = Math.Max(range.StartRow, range.EndRow);
  802. var minCol = Math.Min(range.StartColumn, range.EndColumn);
  803. var maxCol = Math.Max(range.StartColumn, range.EndColumn);
  804. foreach(var (control, element) in elementmap)
  805. {
  806. if(control.Row <= maxRow && control.Row + control.RowSpan - 1 >= minRow
  807. && control.Column <= maxCol && control.Column + control.ColumnSpan - 1 >= minCol)
  808. {
  809. yield return new(control, element);
  810. }
  811. }
  812. }
  813. private IEnumerable<DFLayoutControl> GetSelectedItems(CellRange? range = null) => GetSelectedMaps(range).Select(x => x.Item1);
  814. private void PopulateSelectionMenu(ContextMenu menu)
  815. {
  816. if (Selection is null) return;
  817. if (Selection.IsRowSelection)
  818. {
  819. var nRows = Math.Abs(Selection.EndRow - Selection.StartRow) + 1;
  820. if (nRows == 1)
  821. {
  822. PopulateRowMenu(menu, Selection.StartRow - 1);
  823. }
  824. else
  825. {
  826. menu.AddItem(nRows == 1 ? "Delete Row" : "Delete Rows", null, new Range(Selection.StartRow - 1, Selection.EndRow - 1), DeleteRows);
  827. }
  828. }
  829. else if (Selection.IsColumnSelection)
  830. {
  831. var nColumns = Math.Abs(Selection.EndColumn - Selection.StartColumn) + 1;
  832. if (nColumns == 1)
  833. {
  834. PopulateColumnMenu(menu, Selection.StartColumn - 1);
  835. }
  836. else
  837. {
  838. menu.AddItem(nColumns == 1 ? "Delete Column" : "Delete Columns", null, new Range(Selection.StartColumn - 1, Selection.EndColumn - 1), DeleteColumns);
  839. }
  840. }
  841. else
  842. {
  843. var selectedItems = GetSelectedItems().ToList();
  844. if (selectedItems.Count == 0)
  845. {
  846. PopulateEmptyCellMenu(menu, Selection.ToRange());
  847. }
  848. if (selectedItems.Count == 1)
  849. {
  850. var item = selectedItems.First();
  851. PopulateElementContextMenu(menu, item);
  852. }
  853. else if (selectedItems.Count > 1)
  854. {
  855. menu.AddItem("Delete Items", null, selectedItems, DeleteElements);
  856. }
  857. }
  858. }
  859. private void Selection_MouseRightButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  860. {
  861. if (!IsDesigning || Selection is null) return;
  862. var menu = new ContextMenu();
  863. PopulateSelectionMenu(menu);
  864. if(menu.Items.Count == 0)
  865. {
  866. menu.AddItem("No actions available", null, null, false);
  867. }
  868. menu.IsOpen = true;
  869. }
  870. #endregion
  871. #region Resizing
  872. private CellSelection? Resizer;
  873. private Tuple<int, int> StartDragPosition;
  874. private CellSelection? TopResizeBackground;
  875. private CellSelection? LeftResizeBackground;
  876. private CellSelection? RightResizeBackground;
  877. private CellSelection? BottomResizeBackground;
  878. private DFLayoutControl? ResizingControl;
  879. private CellSelection GetResizeBackground(ref CellSelection? background)
  880. {
  881. if(background is null)
  882. {
  883. background = new CellSelection(0, 0, 0, 0, CellSelection.SelectionTypes.ResizeBackground);
  884. background.PreviewMouseDown += ResizerBackground_PreviewMouseDown;
  885. Children.Add(background);
  886. }
  887. return background;
  888. }
  889. private void ClearResizeBackground(ref CellSelection? background)
  890. {
  891. if(background is not null)
  892. {
  893. Children.Remove(background);
  894. background = null;
  895. }
  896. }
  897. private void ResizerBackground_PreviewMouseDown(object sender, MouseButtonEventArgs e)
  898. {
  899. FinishResize();
  900. }
  901. private void SetResizerBackgroundSize(CellSelection background, int startRow, int startColumn, int endRow, int endColumn)
  902. {
  903. background.SetSize(startRow, startColumn, endRow, endColumn);
  904. background.Visibility = endColumn >= startColumn && endRow >= startRow ? Visibility.Visible : Visibility.Collapsed;
  905. }
  906. private void UpdateResizer(CellRange newSize)
  907. {
  908. if (Resizer is null) return;
  909. Resizer.StartRow = newSize.StartRow;
  910. Resizer.StartColumn = newSize.StartColumn;
  911. Resizer.EndRow = newSize.EndRow;
  912. Resizer.EndColumn = newSize.EndColumn;
  913. SetResizerBackgroundSize(GetResizeBackground(ref LeftResizeBackground), 0, 0, RowDefinitions.Count - 1, newSize.MinColumn - 1);
  914. SetResizerBackgroundSize(GetResizeBackground(ref RightResizeBackground), 0, newSize.MaxColumn + 1, RowDefinitions.Count - 1, ColumnDefinitions.Count - 1);
  915. SetResizerBackgroundSize(GetResizeBackground(ref TopResizeBackground), 0, newSize.MinColumn, newSize.MinRow - 1, newSize.MaxColumn);
  916. SetResizerBackgroundSize(GetResizeBackground(ref BottomResizeBackground), newSize.MaxRow + 1, newSize.MinColumn, RowDefinitions.Count - 1, newSize.MaxColumn);
  917. }
  918. private void ResizeMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
  919. {
  920. if (Resizer is null) return;
  921. if (!Resizer.IsDragging) return;
  922. var (row, column) = GetRowColIndex(e.GetPosition(this));
  923. var newSize = Resizer.ToRange();
  924. switch (Resizer.DragDirection)
  925. {
  926. case CellSelection.Direction.Right:
  927. var startColumn = newSize.MinColumn;
  928. for (int c = column; c >= startColumn; --c)
  929. {
  930. newSize.StartColumn = startColumn;
  931. newSize.EndColumn = Math.Max(c, startColumn);
  932. if (ResizeAllowed(newSize))
  933. {
  934. break;
  935. }
  936. }
  937. break;
  938. case CellSelection.Direction.Left:
  939. var endColumn = newSize.MaxColumn;
  940. for (int c = column; c <= endColumn; ++c)
  941. {
  942. newSize.StartColumn = Math.Min(c, endColumn);
  943. newSize.EndColumn = endColumn;
  944. if (ResizeAllowed(newSize))
  945. {
  946. break;
  947. }
  948. }
  949. break;
  950. case CellSelection.Direction.Bottom:
  951. var startRow = newSize.MinRow;
  952. for (int r = row; r >= startRow; --r)
  953. {
  954. newSize.StartRow = startRow;
  955. newSize.EndRow = Math.Max(r, startRow);
  956. if (ResizeAllowed(newSize))
  957. {
  958. break;
  959. }
  960. }
  961. break;
  962. case CellSelection.Direction.Top:
  963. var endRow = newSize.MaxRow;
  964. for (int r = row; r <= endRow; ++r)
  965. {
  966. newSize.StartRow = Math.Min(r, endRow);
  967. newSize.EndRow = endRow;
  968. if (ResizeAllowed(newSize))
  969. {
  970. break;
  971. }
  972. }
  973. break;
  974. case CellSelection.Direction.None:
  975. return;
  976. }
  977. UpdateResizer(newSize);
  978. }
  979. private bool ResizeAllowed(CellRange range)
  980. {
  981. var items = GetSelectedItems(range).ToList();
  982. if (items.Count > 1) return false;
  983. return items.Count == 0 ||
  984. (items.Count == 1 && items.First() == ResizingControl);
  985. }
  986. private void ClearResize()
  987. {
  988. if (Resizer is null) return;
  989. Children.Remove(Resizer);
  990. Resizer = null;
  991. ResizingControl = null;
  992. ClearResizeBackground(ref LeftResizeBackground);
  993. ClearResizeBackground(ref RightResizeBackground);
  994. ClearResizeBackground(ref TopResizeBackground);
  995. ClearResizeBackground(ref BottomResizeBackground);
  996. }
  997. private void FinishResize()
  998. {
  999. if (Resizer is null) return;
  1000. var range = Resizer.ToRange();
  1001. if(ResizingControl is not null)
  1002. {
  1003. ResizingControl.Row = range.MinRow;
  1004. ResizingControl.Column = range.MinColumn;
  1005. ResizingControl.RowSpan = range.RowSpan;
  1006. ResizingControl.ColumnSpan = range.ColumnSpan;
  1007. }
  1008. ClearResize();
  1009. Render();
  1010. }
  1011. private void ResizeItem(DFLayoutControl control)
  1012. {
  1013. ClearSelection();
  1014. ClearResize();
  1015. Resizer = new CellSelection(
  1016. control.Row, control.Column,
  1017. control.Row + control.RowSpan - 1, control.Column + control.ColumnSpan - 1,
  1018. CellSelection.SelectionTypes.Resizable);
  1019. ResizingControl = control;
  1020. Children.Add(Resizer);
  1021. UpdateResizer(Resizer.ToRange());
  1022. }
  1023. public void HandleKeyDown(KeyEventArgs e)
  1024. {
  1025. if (Resizer is null) return;
  1026. if(e.Key == Key.Enter)
  1027. {
  1028. FinishResize();
  1029. }
  1030. else if(e.Key == Key.Escape)
  1031. {
  1032. ClearResize();
  1033. }
  1034. }
  1035. #endregion
  1036. #region Rows
  1037. private void ShiftDown(int row)
  1038. {
  1039. foreach (var element in form.Elements)
  1040. if (element.Row > row)
  1041. element.Row++;
  1042. else if (element.Row + element.RowSpan - 1 > row)
  1043. element.RowSpan++;
  1044. }
  1045. private void AddRowBeforeClick(int row)
  1046. {
  1047. var length = new GridLength(1.0F, GridUnitType.Auto);
  1048. var result = GridLengthToString(length);
  1049. if (form.RowHeights.Count == 0)
  1050. form.RowHeights.Add(result);
  1051. else
  1052. form.RowHeights.Insert(row, result);
  1053. ShiftDown(row);
  1054. Render();
  1055. }
  1056. private void AddRowAfterClick(int row)
  1057. {
  1058. var length = new GridLength(1.0F, GridUnitType.Auto);
  1059. var result = GridLengthToString(length);
  1060. if (row == form.RowHeights.Count - 1)
  1061. form.RowHeights.Add(result);
  1062. else
  1063. form.RowHeights.Insert(row + 1, result);
  1064. ShiftDown(row + 1);
  1065. Render();
  1066. }
  1067. private void SplitRow(int row)
  1068. {
  1069. foreach (var element in form.Elements)
  1070. if (element.Row > row)
  1071. element.Row++;
  1072. else if (element.Row == row)
  1073. element.RowSpan++;
  1074. else if (element.Row + element.RowSpan - 1 >= row)
  1075. element.RowSpan++;
  1076. }
  1077. private void SplitRowClick(int row)
  1078. {
  1079. var height = StringToGridLength(form.RowHeights[row]);
  1080. var newHeight = height.GridUnitType == GridUnitType.Auto
  1081. ? height
  1082. : new GridLength(height.Value / 2, height.GridUnitType);
  1083. var result = GridLengthToString(newHeight);
  1084. form.RowHeights[row] = result;
  1085. if (row == form.RowHeights.Count - 1)
  1086. form.RowHeights.Add(result);
  1087. else
  1088. form.RowHeights.Insert(row + 1, result);
  1089. SplitRow(row + 1);
  1090. Render();
  1091. }
  1092. private void RowPropertiesClick(int row)
  1093. {
  1094. var length = StringToGridLength(form.RowHeights[row]);
  1095. var editor = new DynamicFormDesignLength(length);
  1096. if (editor.ShowDialog() == true)
  1097. {
  1098. form.RowHeights[row] = GridLengthToString(editor.GridLength);
  1099. Render();
  1100. }
  1101. }
  1102. private void ShiftUp(int row)
  1103. {
  1104. var deletes = new List<DFLayoutControl>();
  1105. foreach (var element in form.Elements)
  1106. if (element.Row > row)
  1107. element.Row--;
  1108. else if (element.Row == row && element.RowSpan <= 1)
  1109. deletes.Add(element);
  1110. else if (element.Row + element.RowSpan - 1 >= row)
  1111. element.RowSpan--;
  1112. foreach (var delete in deletes)
  1113. form.Elements.Remove(delete);
  1114. }
  1115. private void DeleteRows(Range rows)
  1116. {
  1117. for(var row = rows.Max; row >= rows.Min; --row)
  1118. {
  1119. form.RowHeights.RemoveAt(row);
  1120. ShiftUp(row + 1);
  1121. }
  1122. if(form.RowHeights.Count == 0)
  1123. {
  1124. form.RowHeights.Add("Auto");
  1125. }
  1126. Render();
  1127. }
  1128. private void PopulateRowMenu(ContextMenu menu, int row)
  1129. {
  1130. menu.AddItem("Add Row Before", null, row, AddRowBeforeClick);
  1131. menu.AddItem("Add Row After", null, row, AddRowAfterClick);
  1132. menu.AddSeparator();
  1133. menu.AddItem("Split Row", null, row, SplitRowClick);
  1134. var propertiesSeparator = menu.AddSeparator();
  1135. var propertiesMenu = menu.AddItem("Row Properties", null, row, RowPropertiesClick);
  1136. menu.AddSeparator();
  1137. menu.AddItem("Delete Row", null, new Range(row, row), DeleteRows);
  1138. menu.Opened += (o, e) =>
  1139. {
  1140. propertiesSeparator.Visibility = form.RowHeights.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
  1141. propertiesMenu.Visibility = form.RowHeights.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
  1142. };
  1143. }
  1144. private ContextMenu CreateRowMenu(Button button, int row)
  1145. {
  1146. var result = new ContextMenu();
  1147. PopulateRowMenu(result, row);
  1148. button.SetValue(ContextMenuProperty, result);
  1149. return result;
  1150. }
  1151. #endregion
  1152. #region Columns
  1153. private void ShiftRight(int column)
  1154. {
  1155. foreach (var element in form.Elements)
  1156. if (element.Column > column)
  1157. element.Column++;
  1158. else if (element.Column + element.ColumnSpan - 1 > column)
  1159. element.ColumnSpan++;
  1160. }
  1161. private void AddColumnBeforeClick(int column)
  1162. {
  1163. var length = new GridLength(1.0F, form.ColumnWidths.Count == 0 ? GridUnitType.Star : GridUnitType.Auto);
  1164. var result = GridLengthToString(length);
  1165. if (form.ColumnWidths.Count == 0)
  1166. form.ColumnWidths.Add(result);
  1167. else
  1168. form.ColumnWidths.Insert(column, result);
  1169. ShiftRight(column);
  1170. Render();
  1171. }
  1172. private void AddColumnAfterClick(int column)
  1173. {
  1174. var length = new GridLength(1.0F, form.ColumnWidths.Count == 0 ? GridUnitType.Star : GridUnitType.Auto);
  1175. var result = GridLengthToString(length);
  1176. if (column == form.ColumnWidths.Count - 1)
  1177. form.ColumnWidths.Add(result);
  1178. else
  1179. form.ColumnWidths.Insert(column + 1, result);
  1180. ShiftRight(column + 1);
  1181. Render();
  1182. }
  1183. private void SplitColumn(int column)
  1184. {
  1185. foreach (var element in form.Elements)
  1186. if (element.Column > column)
  1187. element.Column++;
  1188. else if (element.Column == column)
  1189. element.ColumnSpan++;
  1190. else if (element.Column + element.ColumnSpan - 1 >= column)
  1191. element.ColumnSpan++;
  1192. }
  1193. private void SplitColumnClick(int column)
  1194. {
  1195. var length = StringToGridLength(form.ColumnWidths[column]);
  1196. var newLength = length.GridUnitType == GridUnitType.Auto
  1197. ? length
  1198. : new GridLength(length.Value / 2, length.GridUnitType);
  1199. var result = GridLengthToString(newLength);
  1200. form.ColumnWidths[column] = result;
  1201. if (column == form.ColumnWidths.Count - 1)
  1202. form.ColumnWidths.Add(result);
  1203. else
  1204. form.ColumnWidths.Insert(column + 1, result);
  1205. SplitColumn(column + 1);
  1206. Render();
  1207. }
  1208. private void ColumnPropertiesClick(int column)
  1209. {
  1210. var length = StringToGridLength(form.ColumnWidths[column]);
  1211. var editor = new DynamicFormDesignLength(length);
  1212. if (editor.ShowDialog() == true)
  1213. {
  1214. form.ColumnWidths[column] = GridLengthToString(editor.GridLength);
  1215. Render();
  1216. }
  1217. }
  1218. private void ShiftLeft(int column)
  1219. {
  1220. var deletes = new List<DFLayoutControl>();
  1221. foreach (var element in form.Elements)
  1222. if (element.Column > column)
  1223. element.Column--;
  1224. else if (element.Column == column && element.ColumnSpan <= 1)
  1225. deletes.Add(element);
  1226. else if (element.Column + element.ColumnSpan - 1 >= column)
  1227. element.ColumnSpan--;
  1228. foreach (var delete in deletes)
  1229. form.Elements.Remove(delete);
  1230. }
  1231. private void DeleteColumns(Range columns)
  1232. {
  1233. for(var column = columns.Max; column >= columns.Min; --column)
  1234. {
  1235. form.ColumnWidths.RemoveAt(column);
  1236. ShiftLeft(column + 1);
  1237. }
  1238. if(form.ColumnWidths.Count == 0)
  1239. {
  1240. form.ColumnWidths.Add("*");
  1241. }
  1242. Render();
  1243. }
  1244. private void PopulateColumnMenu(ContextMenu menu, int column)
  1245. {
  1246. menu.AddItem("Add Column Before", null, column, AddColumnBeforeClick);
  1247. menu.AddItem("Add Column After", null, column, AddColumnAfterClick);
  1248. menu.AddSeparator();
  1249. menu.AddItem("Split Column", null, column, SplitColumnClick);
  1250. var propertiesSeparator = menu.AddSeparator();
  1251. var propertiesMenu = menu.AddItem("Column Properties", null, column, ColumnPropertiesClick);
  1252. menu.AddSeparator();
  1253. menu.AddItem("Delete Column", null, new Range(column, column), DeleteColumns);
  1254. menu.Opened += (o, e) =>
  1255. {
  1256. propertiesSeparator.Visibility = form.ColumnWidths.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
  1257. propertiesMenu.Visibility = form.ColumnWidths.Count > 1 ? Visibility.Visible : Visibility.Collapsed;
  1258. };
  1259. }
  1260. private ContextMenu CreateColumnMenu(Button button, int column)
  1261. {
  1262. var result = new ContextMenu();
  1263. PopulateColumnMenu(result, column);
  1264. button.SetValue(ContextMenuProperty, result);
  1265. return result;
  1266. }
  1267. #endregion
  1268. #region Add Element
  1269. private void AddNewElement<TElement>(DynamicFormElement elementDef, CellRange range)
  1270. where TElement : DFLayoutElement, new()
  1271. {
  1272. TElement? element;
  1273. if (elementDef.CreateElement is not null)
  1274. {
  1275. element = elementDef.CreateElement(elementDef.Tag) as TElement;
  1276. }
  1277. else
  1278. {
  1279. element = new();
  1280. }
  1281. if(element is null)
  1282. {
  1283. return;
  1284. }
  1285. SetControlRange(element, range);
  1286. var result = new FormControlGrid<TElement>().EditItems(new[] { element });
  1287. if (result)
  1288. {
  1289. form.Elements.Add(element);
  1290. Render();
  1291. }
  1292. }
  1293. private void AddElementClick(Tuple<DynamicFormElement, CellRange> tuple)
  1294. {
  1295. var method = typeof(DynamicFormDesignGrid)
  1296. .GetMethod(nameof(AddNewElement), BindingFlags.NonPublic | BindingFlags.Instance)!
  1297. .MakeGenericMethod(tuple.Item1.ElementType);
  1298. method.Invoke(this, new object[] { tuple.Item1, tuple.Item2 });
  1299. }
  1300. private void ElementActionClick(Tuple<DynamicFormElementAction, CellRange> tuple)
  1301. {
  1302. var element = tuple.Item1.OnClick(tuple.Item1.Tag);
  1303. if(element is not null)
  1304. {
  1305. SetControlRange(element, tuple.Item2);
  1306. form.Elements.Add(element);
  1307. Render();
  1308. }
  1309. }
  1310. private void SetControlRange(DFLayoutControl control, CellRange range)
  1311. {
  1312. var minRow = Math.Min(range.StartRow, range.EndRow);
  1313. var maxRow = Math.Max(range.StartRow, range.EndRow);
  1314. var minColumn = Math.Min(range.StartColumn, range.EndColumn);
  1315. var maxColumn = Math.Max(range.StartColumn, range.EndColumn);
  1316. control.Row = minRow;
  1317. control.RowSpan = (maxRow - minRow) + 1;
  1318. control.Column = minColumn;
  1319. control.ColumnSpan = (maxColumn - minColumn) + 1;
  1320. }
  1321. private void CreateLabelClick(CellRange range)
  1322. {
  1323. var label = new DFLayoutLabel();
  1324. SetControlRange(label, range);
  1325. var result = new FormControlGrid<DFLayoutLabel>().EditItems(new[] { label });
  1326. if (result)
  1327. {
  1328. form.Elements.Add(label);
  1329. Render();
  1330. }
  1331. }
  1332. private void CreateHeaderClick(CellRange range)
  1333. {
  1334. var header = new DFLayoutHeader();
  1335. SetControlRange(header, range);
  1336. var result = new FormControlGrid<DFLayoutHeader>().EditItems(new[] { header });
  1337. if (result)
  1338. {
  1339. form.Elements.Add(header);
  1340. Render();
  1341. }
  1342. }
  1343. private void CreateImageClick(CellRange range)
  1344. {
  1345. var image = new DFLayoutImage();
  1346. SetControlRange(image, range);
  1347. var result = new FormControlGrid<DFLayoutImage>().EditItems(new[] { image });
  1348. if (result)
  1349. {
  1350. form.Elements.Add(image);
  1351. Render();
  1352. }
  1353. }
  1354. private void AddVariable(Tuple<DigitalFormVariable, CellRange> tuple)
  1355. {
  1356. if(Activator.CreateInstance(tuple.Item1.FieldType()) is not DFLayoutField field)
  1357. {
  1358. MessageBox.Show(string.Format("{0}: Unknown Type {1}", tuple.Item1.Code, tuple.Item1.VariableType.ToString()));
  1359. return;
  1360. }
  1361. field.Name = tuple.Item1.Code;
  1362. SetControlRange(field, tuple.Item2);
  1363. form.Elements.Add(field);
  1364. form.LoadVariable(tuple.Item1, field);
  1365. Render();
  1366. }
  1367. private void PopulateEmptyCellMenu(ContextMenu menu, CellRange cellRange)
  1368. {
  1369. menu.Items.Clear();
  1370. menu.AddItem("Add Label", null, cellRange, CreateLabelClick);
  1371. menu.AddItem("Add Header", null, cellRange, CreateHeaderClick);
  1372. menu.AddItem("Add Image", null, cellRange, CreateImageClick);
  1373. var fields = menu.AddItem("Add Field", null, null);
  1374. if (OnCreateVariable is not null)
  1375. {
  1376. var variables = fields.AddItem("Create new variable", null, null);
  1377. foreach (var fieldType in DFUtils.GetFieldTypes())
  1378. {
  1379. var caption = fieldType.GetCaption();
  1380. if (string.IsNullOrWhiteSpace(caption))
  1381. {
  1382. caption = CoreUtils.Neatify(fieldType.Name);
  1383. }
  1384. variables.AddItem(caption, null, new Tuple<Type, CellRange>(fieldType, cellRange), (tuple) =>
  1385. {
  1386. var variable = OnCreateVariable?.Invoke(tuple.Item1);
  1387. if (variable is not null)
  1388. {
  1389. _variables.Add(variable);
  1390. AddVariable(new(variable, tuple.Item2));
  1391. }
  1392. });
  1393. }
  1394. }
  1395. var filtered = _variables.Where(x => !x.Hidden && !form.Elements.Any(v => string.Equals((v as DFLayoutField)?.Name, x.Code)));
  1396. fields.AddSeparatorIfNeeded();
  1397. foreach (var variable in filtered)
  1398. fields.AddItem(variable.Code, null, new Tuple<DigitalFormVariable, CellRange>(variable, cellRange), AddVariable);
  1399. fields.RemoveUnnecessarySeparators();
  1400. if(fields.Items.Count == 0)
  1401. {
  1402. menu.Items.Remove(fields);
  1403. }
  1404. var elements = menu.AddItem("Add Object", null, cellRange, null);
  1405. var available = _elements.Where(x => x.Visible && (x.AllowDuplicate || !form.Elements.Any(v => (v as DFLayoutElement)?.GetType() == x.ElementType)))
  1406. .ToArray();
  1407. var cats = available.Select(x => x.Category).Concat(_elementActions.Select(x => x.Category)).Distinct().OrderBy(x => x);
  1408. foreach (var cat in cats)
  1409. {
  1410. var parentMenu = elements;
  1411. if (!string.IsNullOrWhiteSpace(cat))
  1412. {
  1413. parentMenu = elements.AddItem(cat, null, null);
  1414. }
  1415. foreach(var action in _elementActions.Where(x => x.Category == cat))
  1416. {
  1417. parentMenu.AddItem(action.Caption, action.Image, new Tuple<DynamicFormElementAction, CellRange>(action, cellRange), ElementActionClick);
  1418. }
  1419. parentMenu.AddSeparatorIfNeeded();
  1420. foreach (var element in available.Where(x => string.Equals(x.Category, cat)))
  1421. parentMenu.AddItem(element.Caption, null, new Tuple<DynamicFormElement, CellRange>(element, cellRange), AddElementClick);
  1422. parentMenu.RemoveUnnecessarySeparators();
  1423. }
  1424. if (elements.Items.Count == 0)
  1425. menu.Items.Remove(elements);
  1426. }
  1427. private ContextMenu CreateEmptyCellMenu(Border border, int row, int column)
  1428. {
  1429. var result = new ContextMenu();
  1430. result.Opened += (o, e) =>
  1431. {
  1432. PopulateEmptyCellMenu(result, new CellRange(row, column));
  1433. };
  1434. border.SetValue(ContextMenuProperty, result);
  1435. return result;
  1436. }
  1437. #endregion
  1438. #region Element Context Menu
  1439. private void DeleteElements(IEnumerable<DFLayoutControl> controls)
  1440. {
  1441. foreach(var control in controls)
  1442. {
  1443. if (form.Elements.Contains(control))
  1444. {
  1445. form.Elements.Remove(control);
  1446. }
  1447. }
  1448. Render();
  1449. }
  1450. private void DeleteElementClick(DFLayoutControl control)
  1451. {
  1452. if (form.Elements.Contains(control))
  1453. {
  1454. form.Elements.Remove(control);
  1455. Render();
  1456. }
  1457. }
  1458. private void ElementPropertiesClick(DFLayoutControl control)
  1459. {
  1460. if(!elementgrids.TryGetValue(control.GetType(), out var grid))
  1461. {
  1462. var type = typeof(FormControlGrid<>).MakeGenericType(control.GetType());
  1463. grid = (Activator.CreateInstance(type) as IDynamicGrid)!;
  1464. elementgrids[control.GetType()] = grid;
  1465. }
  1466. control.CommitChanges();
  1467. if (grid.EditItems(new[] { control }))
  1468. {
  1469. Render();
  1470. }
  1471. }
  1472. private void EditVariableClick(DFLayoutField field)
  1473. {
  1474. var variable = _variables.FirstOrDefault(x => x.Code == field.Name);
  1475. if (variable is null) return;
  1476. if(OnEditVariable?.Invoke(variable) == true)
  1477. {
  1478. field.LoadFromString(variable.Parameters);
  1479. }
  1480. }
  1481. private void ConvertToHeaderClick(DFLayoutLabel label)
  1482. {
  1483. var header = new DFLayoutHeader
  1484. {
  1485. Row = label.Row,
  1486. RowSpan = label.RowSpan,
  1487. Column = label.Column,
  1488. ColumnSpan = label.ColumnSpan,
  1489. Collapsed = false,
  1490. Header = label.Caption
  1491. };
  1492. header.Style.Synchronise(label.Style);
  1493. header.Style.IsBold = true;
  1494. form.Elements.Remove(label);
  1495. form.Elements.Add(header);
  1496. Render();
  1497. }
  1498. private void ConvertToLabelClick(DFLayoutHeader header)
  1499. {
  1500. var label = new DFLayoutLabel
  1501. {
  1502. Row = header.Row,
  1503. RowSpan = header.RowSpan,
  1504. Column = header.Column,
  1505. ColumnSpan = header.ColumnSpan,
  1506. Caption = header.Header
  1507. };
  1508. label.Style.Synchronise(header);
  1509. label.Style.IsBold = false;
  1510. form.Elements.Remove(header);
  1511. form.Elements.Add(label);
  1512. Render();
  1513. }
  1514. private void PopulateElementContextMenu(ContextMenu menu, DFLayoutControl control)
  1515. {
  1516. var selectedItems = GetSelectedItems().ToList();
  1517. if (selectedItems.Count > 1 && selectedItems.Contains(control))
  1518. {
  1519. PopulateSelectionMenu(menu);
  1520. if(menu.Items.Count > 0) return;
  1521. }
  1522. menu.AddItem("Edit Properties", null, control, ElementPropertiesClick);
  1523. if (OnEditVariable is not null && control is DFLayoutField field)
  1524. {
  1525. menu.AddItem("Edit Variable", null, field, EditVariableClick);
  1526. }
  1527. else if (control is DFLayoutLabel label)
  1528. {
  1529. menu.AddItem("Convert to Header", null, label, ConvertToHeaderClick);
  1530. }
  1531. else if (control is DFLayoutHeader header)
  1532. {
  1533. menu.AddItem("Convert to Label", null, header, ConvertToLabelClick);
  1534. }
  1535. else if(control is DFLayoutElement element)
  1536. {
  1537. CustomiseElementContextMenu?.Invoke(menu, element);
  1538. }
  1539. menu.AddSeparatorIfNeeded();
  1540. menu.AddItem("Resize Item", null, control, ResizeItem);
  1541. menu.AddItem("Delete Item", null, control, DeleteElementClick);
  1542. }
  1543. private ContextMenu CreateElementContextMenu(FrameworkElement element, DFLayoutControl control)
  1544. {
  1545. var result = new ContextMenu();
  1546. result.Opened += (s, e) =>
  1547. {
  1548. result.Items.Clear();
  1549. PopulateElementContextMenu(result, control);
  1550. };
  1551. element.SetValue(ContextMenuProperty, result);
  1552. return result;
  1553. }
  1554. #endregion
  1555. #endregion
  1556. #region Render
  1557. private static void SetDimensions(FrameworkElement element, int row, int column, int rowspan, int colspan, int offset)
  1558. {
  1559. if (column <= 0) return;
  1560. if (row <= 0) return;
  1561. element.MinHeight = 50.0F;
  1562. element.MinWidth = 50.0F;
  1563. element.SetGridPosition(row - offset, column - offset, rowspan, colspan);
  1564. }
  1565. private Border CreateBorder(int row, int column, int rowspan, int colspan, int offset, bool horzstar, bool vertstar)
  1566. {
  1567. var border = new Border();
  1568. if (ShowBorders)
  1569. {
  1570. border.BorderThickness = new Thickness(
  1571. 0.0F,//!IsDesigning && column == 1 - offset ? 0.00F /*0.75F*/ : 0.0F,
  1572. 0.0F,//!IsDesigning && row == 1 - offset ? 0.00F /*0.75F*/ : 0.0F,
  1573. column - offset == ColumnDefinitions.Count - 1 ? horzstar ? 0.00F : 0.75F : 0.75F,
  1574. row - offset == RowDefinitions.Count - 1 ? vertstar ? 0.00F : 0.75F : 0.75F
  1575. );
  1576. border.BorderBrush = BorderBrush;
  1577. }
  1578. border.Background = BackgroundBrush;
  1579. SetDimensions(border, row, column, rowspan, colspan, offset);
  1580. return border;
  1581. }
  1582. private static BitmapImage HeaderClosed =Wpf.Resources.rightarrow.AsBitmapImage(32, 32);
  1583. private static BitmapImage HeaderOpen =Wpf.Resources.downarrow.AsBitmapImage(32, 32);
  1584. private FrameworkElement CreateHeader(DFLayoutHeader header)
  1585. {
  1586. var formHeader = new FormHeader
  1587. {
  1588. Collapsed = header.Collapsed,
  1589. HeaderText = header.Header
  1590. };
  1591. formHeader.CollapsedChanged += (o, c) =>
  1592. {
  1593. CollapseRows(formHeader, c);
  1594. };
  1595. if (IsDesigning)
  1596. {
  1597. formHeader.IsEnabled = false;
  1598. }
  1599. return formHeader;
  1600. }
  1601. // DFLayoutField -> IDynamicFormFieldControl
  1602. private static Dictionary<Type, Type>? _fieldControls;
  1603. private DynamicFormControl? CreateFieldControl(DFLayoutField field)
  1604. {
  1605. if (_fieldControls == null)
  1606. {
  1607. _fieldControls = new();
  1608. foreach (var controlType in CoreUtils.Entities.Where(x => x.IsClass && !x.IsGenericType && x.HasInterface<IDynamicFormFieldControl>()))
  1609. {
  1610. var superDefinition = controlType.GetSuperclassDefinition(typeof(DynamicFormFieldControl<,,,>));
  1611. if (superDefinition != null)
  1612. {
  1613. _fieldControls[superDefinition.GenericTypeArguments[0]] = controlType;
  1614. }
  1615. }
  1616. }
  1617. var fieldControlType = _fieldControls.GetValueOrDefault(field.GetType());
  1618. if (fieldControlType is not null)
  1619. {
  1620. var element = (Activator.CreateInstance(fieldControlType) as DynamicFormControl)!;
  1621. if(element is IDynamicFormFieldControl fieldControl)
  1622. {
  1623. fieldControl.FieldChangedEvent += () =>
  1624. {
  1625. ChangeField(field.Name);
  1626. };
  1627. }
  1628. return element;
  1629. }
  1630. return null;
  1631. }
  1632. private DynamicFormControl? CreateFieldPlaceholder(DFLayoutField field)
  1633. {
  1634. var controlType = typeof(DFFieldPlaceholderControl<>).MakeGenericType(field.GetType());
  1635. return Activator.CreateInstance(controlType) as DynamicFormControl;
  1636. }
  1637. private DynamicFormControl? CreateControl(DFLayoutControl item)
  1638. {
  1639. if (item is DFLayoutField field)
  1640. {
  1641. if (IsDesigning)
  1642. {
  1643. return CreateFieldPlaceholder(field);
  1644. }
  1645. return CreateFieldControl(field);
  1646. }
  1647. else if (item is DFLayoutElement)
  1648. {
  1649. return IsDesigning
  1650. ? new DFElementPlaceholderControl()
  1651. : new DFElementControl();
  1652. }
  1653. else if (item is DFLayoutLabel)
  1654. {
  1655. return new DFLabelControl();
  1656. }
  1657. else if (item is DFLayoutHeader)
  1658. {
  1659. return new DFHeaderControl();
  1660. }
  1661. else if (item is DFLayoutImage)
  1662. {
  1663. return new DFImageControl();
  1664. }
  1665. return null;
  1666. }
  1667. private FrameworkElement? CreateElement(DFLayoutControl item)
  1668. {
  1669. var control = CreateControl(item);
  1670. if(control != null)
  1671. {
  1672. control.FormDesignGrid = this;
  1673. control.SetControl(item);
  1674. }
  1675. return control;
  1676. }
  1677. private Brush GetItemBackgroundBrush(DFLayoutControl item, Color? colour = null)
  1678. {
  1679. if(colour != null)
  1680. {
  1681. var colourValue = colour.Value;
  1682. return new SolidColorBrush(new System.Windows.Media.Color { R = colourValue.R, G = colourValue.G, B = colourValue.B, A = colourValue.A });
  1683. }
  1684. if (item is DFLayoutField field)
  1685. return field.GetPropertyValue<bool>("Required") ? RequiredFieldBrush : FieldBrush;
  1686. else
  1687. return IsDesigning ? FieldBrush : BackgroundBrush;
  1688. }
  1689. private void RenderElement(DFLayoutControl item, int offset, bool horzstar, bool vertstar)
  1690. {
  1691. var border = CreateBorder(item.Row, item.Column, item.RowSpan, item.ColumnSpan, offset, horzstar, vertstar);
  1692. border.Background = GetItemBackgroundBrush(item);
  1693. if (!ShowBorders)
  1694. border.Padding = new Thickness(
  1695. item.Column == 1 ? 4 : 2,
  1696. item.Row == 1 ? 4 : 2,
  1697. item.Column + item.ColumnSpan - 1 == ColumnDefinitions.Count ? 4 : 2,
  1698. item.Row + item.RowSpan - 1 == RowDefinitions.Count ? 4 : 2
  1699. );
  1700. else
  1701. border.Padding = new Thickness(5);
  1702. var element = CreateElement(item);
  1703. border.Child = element;
  1704. Children.Add(border);
  1705. if (IsDesigning)
  1706. {
  1707. CreateElementContextMenu(border, item);
  1708. }
  1709. borderMap[item] = border;
  1710. if (element != null)
  1711. {
  1712. if(item is DFLayoutField)
  1713. {
  1714. element.IsEnabled = element.IsEnabled && !IsReadOnly;
  1715. }
  1716. elementmap[item] = element;
  1717. element.HorizontalAlignment = GetHorizontalAlignment(item.HorizontalAlignment);
  1718. element.VerticalAlignment = GetVerticalAlignment(item.VerticalAlignment);
  1719. if (IsDesigning)
  1720. {
  1721. CreateElementContextMenu(element, item);
  1722. }
  1723. }
  1724. }
  1725. private void AfterRender()
  1726. {
  1727. if (!IsDesigning)
  1728. {
  1729. foreach (var header in elementmap.Where(x => x.Value is DFHeaderControl head).Select(x => x.Value).Cast<DFHeaderControl>())
  1730. {
  1731. if (header.Header.Collapsed)
  1732. {
  1733. CollapseRows(header.Header, true);
  1734. }
  1735. }
  1736. }
  1737. OnAfterRender?.Invoke(this);
  1738. }
  1739. private void Render()
  1740. {
  1741. ClearSelection();
  1742. ClearResize();
  1743. foreach (var item in elementmap.Keys)
  1744. {
  1745. var e = elementmap[item];
  1746. if (VisualTreeHelper.GetParent(e) is Border parent)
  1747. parent.Child = null;
  1748. }
  1749. elementmap.Clear();
  1750. Children.Clear();
  1751. ColumnDefinitions.Clear();
  1752. RowDefinitions.Clear();
  1753. if (form == null)
  1754. return;
  1755. foreach (var column in form.ColumnWidths)
  1756. ColumnDefinitions.Add(new ColumnDefinition { Width = StringToGridLength(column) });
  1757. foreach (var row in form.RowHeights)
  1758. RowDefinitions.Add(new RowDefinition { Height = StringToGridLength(row), Tag = new RowData(row) });
  1759. var horzstar = ColumnDefinitions.Any(x => x.Width.IsStar);
  1760. var vertstar = RowDefinitions.Any(x => x.Height.IsStar);
  1761. var offset = 1;
  1762. if (IsDesigning)
  1763. {
  1764. ColumnDefinitions.Insert(0, new ColumnDefinition { Width = new GridLength(1, GridUnitType.Auto) });
  1765. RowDefinitions.Insert(0, new RowDefinition { Height = new GridLength(1, GridUnitType.Auto) });
  1766. var topleft = new Button();
  1767. topleft.SetValue(RowProperty, 0);
  1768. topleft.SetValue(ColumnProperty, 0);
  1769. topleft.Content =
  1770. ""; // new Image() { Source = _designing ? Wpf.Resources.view.AsBitmapImage() : Wpf.Resources.design.AsBitmapImage() };
  1771. topleft.BorderBrush = BorderBrush;
  1772. topleft.BorderThickness = new Thickness(
  1773. 0.00F,
  1774. 0.00F,
  1775. 0.75F,
  1776. 0.75F
  1777. );
  1778. topleft.Background = BackgroundBrush;
  1779. //topleft.Click += (o, e) =>
  1780. //{
  1781. // Designing = !Designing;
  1782. //};
  1783. Children.Add(topleft);
  1784. for (var i = 1; i < ColumnDefinitions.Count; i++)
  1785. {
  1786. var Button = new Button();
  1787. Button.SetValue(RowProperty, 0);
  1788. Button.SetValue(ColumnProperty, i);
  1789. Button.Content = FormatGridLength(ColumnDefinitions[i].Width, ColumnDefinitions.Select(x => x.Width));
  1790. Button.BorderBrush = BorderBrush;
  1791. Button.BorderThickness = new Thickness(
  1792. 0.00F, //(i == 1) ? 0.75F : 0.0F,
  1793. 0.00F, //0.75F,
  1794. i == ColumnDefinitions.Count - 1 ? horzstar ? 0.00F : 0.75F : 0.75F,
  1795. 0.75F
  1796. );
  1797. Button.Background = BackgroundBrush;
  1798. Button.Padding = new Thickness(10);
  1799. Button.MinHeight = 35;
  1800. CreateColumnMenu(Button, i - 1);
  1801. AddClick(Button, i - 1, ColumnPropertiesClick);
  1802. Children.Add(Button);
  1803. }
  1804. for (var i = 1; i < RowDefinitions.Count; i++)
  1805. {
  1806. var Button = new Button();
  1807. Button.SetValue(RowProperty, i);
  1808. Button.SetValue(ColumnProperty, 0);
  1809. Button.Content = FormatGridLength(RowDefinitions[i].Height, RowDefinitions.Select(x => x.Height));
  1810. Button.BorderBrush = BorderBrush;
  1811. Button.BorderThickness = new Thickness(
  1812. 0.00F, //0.75F,
  1813. 0.00F, //(i == 1) ? 0.75F : 0.0F,
  1814. 0.75F,
  1815. i == RowDefinitions.Count - 1 ? vertstar ? 0.00F : 0.75F : 0.75F
  1816. );
  1817. Button.Background = BackgroundBrush;
  1818. Button.Padding = new Thickness(10);
  1819. CreateRowMenu(Button, i - 1);
  1820. AddClick(Button, i - 1, RowPropertiesClick);
  1821. Children.Add(Button);
  1822. }
  1823. offset = 0;
  1824. }
  1825. var filledcells = new List<Point>();
  1826. foreach (var item in form.GetElements(IsDesigning))
  1827. {
  1828. try
  1829. {
  1830. if(item.Row > 0 && item.Column > 0)
  1831. {
  1832. RenderElement(item, offset, horzstar, vertstar);
  1833. for (var c = item.Column; c < item.Column + item.ColumnSpan; c++)
  1834. for (var r = item.Row; r < item.Row + item.RowSpan; r++)
  1835. filledcells.Add(new Point(c, r));
  1836. }
  1837. }
  1838. catch (Exception e)
  1839. {
  1840. Logger.Send(LogType.Error, "", string.Format("*** Unknown Error: {0}\n{1}", e.Message, e.StackTrace));
  1841. }
  1842. }
  1843. for (var c = 1; c <= form.ColumnWidths.Count; c++)
  1844. for (var r = 1; r <= form.RowHeights.Count; r++)
  1845. if (!filledcells.Any(x => x.X.Equals(c) && x.Y.Equals(r)))
  1846. {
  1847. var border = CreateBorder(r, c, 1, 1, offset, horzstar, vertstar);
  1848. if (IsDesigning)
  1849. {
  1850. CreateEmptyCellMenu(border, r, c);
  1851. }
  1852. Children.Add(border);
  1853. }
  1854. AfterRender();
  1855. }
  1856. #endregion
  1857. /// <summary>
  1858. /// Renders the form; after this is called, any changes to properties triggers a refresh.
  1859. /// </summary>
  1860. /// <remarks>
  1861. /// This should be called before <see cref="LoadValues(Dictionary{string, object})"/> or <see cref="SaveValues"/>
  1862. /// </remarks>
  1863. public void Initialize()
  1864. {
  1865. GridInitialized = true;
  1866. CheckRefresh(false);
  1867. }
  1868. public void Refresh()
  1869. {
  1870. CheckRefresh(false);
  1871. }
  1872. private void CheckRefresh(bool keepValues = true)
  1873. {
  1874. if (!GridInitialized) return;
  1875. if (_mode == FormMode.Designing)
  1876. {
  1877. Render();
  1878. }
  1879. else if(keepValues)
  1880. {
  1881. var values = SaveValues();
  1882. Render();
  1883. LoadValues(values.ToLoadStorage());
  1884. }
  1885. else
  1886. {
  1887. Render();
  1888. Form.EvaluateExpressions();
  1889. }
  1890. }
  1891. #region Fields
  1892. private void ChangeField(string fieldName)
  1893. {
  1894. if (!_changing)
  1895. {
  1896. form.ChangeField(fieldName);
  1897. _isChanged = true;
  1898. OnChanged?.Invoke(this, fieldName);
  1899. }
  1900. }
  1901. private IDynamicFormFieldControl? GetFieldControl(DFLayoutField field)
  1902. {
  1903. return elementmap.GetValueOrDefault(field) as IDynamicFormFieldControl;
  1904. }
  1905. private void LoadFieldValue(string fieldName, DFLoadStorageEntry entry)
  1906. {
  1907. var field = form.Elements.FirstOrDefault(x => string.Equals(fieldName, (x as DFLayoutField)?.Name)) as DFLayoutField;
  1908. if (field != null)
  1909. {
  1910. var fieldControl = GetFieldControl(field);
  1911. if (fieldControl != null)
  1912. {
  1913. string? property = (DataModel != null) ? field.GetPropertyValue<string>("Property") : null;
  1914. if (!property.IsNullOrWhiteSpace())
  1915. fieldControl.SetValue(DataModel!.GetEntityValue(property));
  1916. else
  1917. fieldControl.Deserialize(entry);
  1918. }
  1919. }
  1920. }
  1921. public void SetFieldValue(string fieldName, object? value)
  1922. {
  1923. var field = form.Elements.FirstOrDefault(x => string.Equals(fieldName, (x as DFLayoutField)?.Name)) as DFLayoutField;
  1924. if (field != null)
  1925. {
  1926. var fieldControl = GetFieldControl(field);
  1927. if (fieldControl != null)
  1928. {
  1929. string? property = (DataModel != null) ? field.GetPropertyValue<string>("Property") : null;
  1930. if (!property.IsNullOrWhiteSpace())
  1931. fieldControl.SetValue(DataModel!.GetEntityValue(property));
  1932. else
  1933. fieldControl.SetValue(value);
  1934. }
  1935. }
  1936. }
  1937. private void GetFieldValue(DFLayoutField field, DFSaveStorageEntry storage, out object? entityValue)
  1938. {
  1939. var fieldControl = GetFieldControl(field);
  1940. if(fieldControl != null)
  1941. {
  1942. entityValue = fieldControl.GetEntityValue();
  1943. fieldControl.Serialize(storage);
  1944. }
  1945. else
  1946. {
  1947. entityValue = null;
  1948. }
  1949. }
  1950. public object? GetFieldValue(string fieldName)
  1951. {
  1952. var field = form.Elements.Where(x => (x as DFLayoutField)?.Name == fieldName).FirstOrDefault() as DFLayoutField;
  1953. if (field is null)
  1954. {
  1955. return null;
  1956. }
  1957. var fieldControl = GetFieldControl(field);
  1958. return fieldControl?.GetValue();
  1959. }
  1960. public object? GetFieldData(string fieldName, string dataField)
  1961. {
  1962. var field = form.Elements.Where(x => (x as DFLayoutField)?.Name == fieldName).FirstOrDefault() as DFLayoutField;
  1963. if (field is null)
  1964. {
  1965. return null;
  1966. }
  1967. var fieldControl = GetFieldControl(field);
  1968. return fieldControl?.GetData(dataField);
  1969. }
  1970. public void SetFieldColour(string fieldName, Color? colour)
  1971. {
  1972. var field = form.Elements.Where(x => (x as DFLayoutField)?.Name == fieldName).FirstOrDefault() as DFLayoutField;
  1973. if (field is null || !borderMap.TryGetValue(field, out var border))
  1974. {
  1975. return;
  1976. }
  1977. border.Background = GetItemBackgroundBrush(field, colour);
  1978. }
  1979. /// <summary>
  1980. /// Load values into editor; Must be called after <see cref="Initialize"/>.
  1981. /// </summary>
  1982. /// <remarks>
  1983. /// Resets <see cref="IsChanged"/>.
  1984. /// </remarks>
  1985. /// <param name="values">A storage object.</param>
  1986. public void LoadValues(DFLoadStorage values)
  1987. {
  1988. _changing = true;
  1989. InitializeEntityValues();
  1990. foreach (var (key, value) in values.Items())
  1991. {
  1992. if (!key.Contains('.'))
  1993. {
  1994. LoadFieldValue(key, values.GetEntry(key));
  1995. }
  1996. }
  1997. Form.EvaluateExpressions();
  1998. _changing = false;
  1999. _isChanged = false;
  2000. }
  2001. public void InitializeEntityValues()
  2002. {
  2003. _changing = true;
  2004. foreach (var field in form.Elements.OfType<DFLayoutField>())
  2005. {
  2006. var property = DataModel != null ? field.GetPropertyValue<string>("Property") : null;
  2007. if (!property.IsNullOrWhiteSpace())
  2008. {
  2009. var fieldControl = GetFieldControl(field);
  2010. if(fieldControl != null)
  2011. {
  2012. fieldControl.SetValue(DataModel!.GetEntityValue(property));
  2013. }
  2014. }
  2015. }
  2016. Form.EvaluateExpressions();
  2017. _changing = false;
  2018. _isChanged = false;
  2019. }
  2020. /// <summary>
  2021. /// Takes values from editors and saves them to a dictionary; must be called after <see cref="Initialize"/>.
  2022. /// </summary>
  2023. /// <returns>A dictionary of <see cref="DigitalFormVariable.Code"/> -> value.</returns>
  2024. public DFSaveStorage SaveValues()
  2025. {
  2026. var result = new DFSaveStorage();
  2027. foreach (var formElement in form.Elements)
  2028. if (formElement is DFLayoutField field)
  2029. {
  2030. GetFieldValue(field, result.GetEntry(field.Name), out var entityValue);
  2031. if(DataModel != null)
  2032. {
  2033. var property = field.GetPropertyValue<string>("Property");
  2034. if (!string.IsNullOrWhiteSpace(property))
  2035. DataModel.SetEntityValue(property, entityValue);
  2036. }
  2037. }
  2038. return result;
  2039. }
  2040. public bool Validate(out List<string> messages)
  2041. {
  2042. messages = new List<string>();
  2043. var valid = true;
  2044. foreach(var formElement in form.Elements)
  2045. {
  2046. if(formElement is DFLayoutField field)
  2047. {
  2048. var fieldControl = GetFieldControl(field);
  2049. if(fieldControl != null && !fieldControl.Validate(out var message))
  2050. {
  2051. messages.Add(message);
  2052. valid = false;
  2053. }
  2054. }
  2055. }
  2056. return valid;
  2057. }
  2058. #endregion
  2059. }
  2060. }