DynamicGridTreeUIComponent.cs 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090
  1. using InABox.Clients;
  2. using InABox.Core;
  3. using InABox.Wpf;
  4. using InABox.WPF;
  5. using Syncfusion.Data;
  6. using Syncfusion.UI.Xaml.Grid;
  7. using Syncfusion.UI.Xaml.ScrollAxis;
  8. using Syncfusion.UI.Xaml.TreeGrid;
  9. using Syncfusion.UI.Xaml.TreeGrid.Helpers;
  10. using System;
  11. using System.Collections.Generic;
  12. using System.ComponentModel;
  13. using System.Linq;
  14. using System.Linq.Expressions;
  15. using System.Text;
  16. using System.Threading.Tasks;
  17. using System.Windows;
  18. using System.Windows.Controls;
  19. using System.Windows.Data;
  20. using System.Windows.Input;
  21. using System.Windows.Media;
  22. using System.Windows.Media.Imaging;
  23. using Syncfusion.UI.Xaml.TreeGrid.Filtering;
  24. namespace InABox.DynamicGrid;
  25. public enum DynamicTreeGridLines
  26. {
  27. Both,
  28. Horizontal,
  29. Vertical,
  30. None
  31. }
  32. public enum DynamicTreeGridExpandMode
  33. {
  34. All,
  35. Root,
  36. None
  37. }
  38. public class DynamicGridTreeUIComponent<T> : IDynamicGridUIComponent<T>, IDynamicGridGridUIComponent<T>
  39. where T : BaseObject, new()
  40. {
  41. private IDynamicGridUIComponentParent<T> _parent;
  42. public IDynamicGridUIComponentParent<T> Parent
  43. {
  44. get => _parent;
  45. set
  46. {
  47. _parent = value;
  48. CellBackgroundConverter = new DynamicGridCellStyleConverter<System.Windows.Media.Brush?>(Parent, GetCellBackground);
  49. CellForegroundConverter = new DynamicGridCellStyleConverter<System.Windows.Media.Brush?>(Parent, GetCellForeground);
  50. CellFontSizeConverter = new DynamicGridCellStyleConverter<double?>(Parent, GetCellFontSize);
  51. CellFontStyleConverter = new DynamicGridCellStyleConverter<System.Windows.FontStyle?>(Parent, GetCellFontStyle);
  52. CellFontWeightConverter = new DynamicGridCellStyleConverter<System.Windows.FontWeight?>(Parent, GetCellFontWeight);
  53. Parent.AddHiddenColumn(IDColumn.Property);
  54. Parent.AddHiddenColumn(ParentColumn.Property);
  55. }
  56. }
  57. private Column<T> IDColumn;
  58. private Column<T> ParentColumn;
  59. private ContextMenu _menu;
  60. private SfTreeGrid _tree;
  61. private readonly ContextMenu ColumnsMenu;
  62. public event OnContextMenuOpening OnContextMenuOpening;
  63. FrameworkElement IDynamicGridUIComponent<T>.Control => _tree;
  64. private bool _shownumbers = false;
  65. public bool ShowNumbers
  66. {
  67. get => _shownumbers;
  68. set
  69. {
  70. _shownumbers = value;
  71. //_tree.Columns[1].Width = value ? 50 : 0;
  72. }
  73. }
  74. private bool _showHeader = false;
  75. public bool ShowHeader
  76. {
  77. get => _showHeader;
  78. set
  79. {
  80. _showHeader = value;
  81. _tree.HeaderRowHeight = value ? 30 : 0;
  82. }
  83. }
  84. private bool _autoSizeExpander = false;
  85. public bool AutoSizeExpander
  86. {
  87. get => _autoSizeExpander;
  88. set
  89. {
  90. _autoSizeExpander = value;
  91. _tree.AllowAutoSizingExpanderColumn = value;
  92. }
  93. }
  94. private DynamicTreeGridLines _gridLines = DynamicTreeGridLines.Both;
  95. public DynamicTreeGridLines GridLines
  96. {
  97. get => _gridLines;
  98. set
  99. {
  100. _gridLines = value;
  101. _tree.GridLinesVisibility = value switch
  102. {
  103. DynamicTreeGridLines.Both => GridLinesVisibility.Both,
  104. DynamicTreeGridLines.Vertical => GridLinesVisibility.Vertical,
  105. DynamicTreeGridLines.Horizontal => GridLinesVisibility.Horizontal,
  106. _ => GridLinesVisibility.None,
  107. };
  108. }
  109. }
  110. public DynamicTreeGridExpandMode ExpandMode
  111. {
  112. get
  113. {
  114. return _tree.AutoExpandMode switch
  115. {
  116. AutoExpandMode.AllNodesExpanded => DynamicTreeGridExpandMode.All,
  117. AutoExpandMode.RootNodesExpanded => DynamicTreeGridExpandMode.Root,
  118. _ => DynamicTreeGridExpandMode.None,
  119. };
  120. }
  121. set
  122. {
  123. _tree.AutoExpandMode = value switch
  124. {
  125. DynamicTreeGridExpandMode.All => AutoExpandMode.AllNodesExpanded,
  126. DynamicTreeGridExpandMode.Root => AutoExpandMode.RootNodesExpanded,
  127. _ => AutoExpandMode.None
  128. };
  129. }
  130. }
  131. private double minRowHeight = 30D;
  132. private double maxRowHeight = 30D;
  133. public double MinRowHeight
  134. {
  135. get => minRowHeight;
  136. set
  137. {
  138. minRowHeight = value;
  139. CalculateRowHeight();
  140. }
  141. }
  142. public double MaxRowHeight
  143. {
  144. get => maxRowHeight;
  145. set
  146. {
  147. maxRowHeight = value;
  148. CalculateRowHeight();
  149. }
  150. }
  151. #region IDynamicGridGridUIComponent
  152. IList<DynamicColumnBase> IDynamicGridGridUIComponent<T>.ColumnList => ColumnList;
  153. int IDynamicGridGridUIComponent<T>.RowHeight => (int)RowHeight;
  154. #endregion
  155. private DynamicGridCellStyleConverter<System.Windows.Media.Brush?> CellBackgroundConverter;
  156. private DynamicGridCellStyleConverter<System.Windows.Media.Brush?> CellForegroundConverter;
  157. private DynamicGridCellStyleConverter<double?> CellFontSizeConverter;
  158. private DynamicGridCellStyleConverter<System.Windows.FontStyle?> CellFontStyleConverter;
  159. private DynamicGridCellStyleConverter<System.Windows.FontWeight?> CellFontWeightConverter;
  160. protected virtual Brush? GetCellBackground(CoreRow row, DynamicColumnBase column) => null;
  161. protected virtual Brush? GetCellForeground(CoreRow row, DynamicColumnBase column) => null;
  162. protected virtual double? GetCellFontSize(CoreRow row, DynamicColumnBase column) => null;
  163. protected virtual FontStyle? GetCellFontStyle(CoreRow row, DynamicColumnBase column) => null;
  164. protected virtual FontWeight? GetCellFontWeight(CoreRow row, DynamicColumnBase column) => null;
  165. public DynamicGridTreeUIComponent(Expression<Func<T, Guid>> idColumn, Expression<Func<T, Guid>> parentIDColumn)
  166. {
  167. IDColumn = new Column<T>(CoreUtils.GetFullPropertyName(idColumn, "."));
  168. ParentColumn = new Column<T>(CoreUtils.GetFullPropertyName(parentIDColumn, "."));
  169. ColumnsMenu = new ContextMenu();
  170. ColumnsMenu.Opened += ColumnsMenu_ContextMenuOpening;
  171. _tree = new SfTreeGrid();
  172. _tree.ChildPropertyName = "Children";
  173. //_tree.ParentPropertyName = "Parent";
  174. _tree.AutoGenerateColumns = false;
  175. ExpandMode = DynamicTreeGridExpandMode.All;
  176. //_tree.NodeCollapsing += (o, e) => { e.Cancel = true; };
  177. //_tree.HeaderRowHeight = 0D;
  178. _tree.HeaderRowHeight = 30;
  179. _tree.HeaderContextMenu = ColumnsMenu;
  180. _tree.SelectionChanging += _tree_SelectionChanging;
  181. _tree.SelectionChanged += _tree_SelectionChanged;
  182. _tree.AllowSelectionOnExpanderClick = false;
  183. _tree.AllowAutoSizingExpanderColumn = false;
  184. _tree.CellTapped += _tree_CellTapped;
  185. _tree.CellDoubleTapped += _tree_CellDoubleTapped;
  186. _tree.KeyUp += _tree_KeyUp;
  187. _tree.CellToolTipOpening += _tree_CellToolTipOpening;
  188. _menu = new ContextMenu();
  189. var additem = new MenuItem() { Header = "Add Child Folder" };
  190. additem.Click += (o, e) => { DoAddItem((_tree.SelectedItem as CoreTreeNode)!.ID, true); };
  191. _menu.Items.Add(additem);
  192. _tree.ContextMenuOpening += _tree_ContextMenuOpening;
  193. _tree.ContextMenu = _menu;
  194. _tree.Background = new SolidColorBrush(Colors.DimGray);
  195. var cellStyle = new Style(typeof(TreeGridRowControl));
  196. cellStyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.White)));
  197. _tree.RowStyle = cellStyle;
  198. var filterstyle = new Style(typeof(TreeGridFilterControl));
  199. filterstyle.Setters.Add(new Setter(TreeGridFilterControl.SortOptionVisibilityProperty, Visibility.Collapsed));
  200. filterstyle.Setters.Add(new Setter(TreeGridFilterControl.ImmediateUpdateColumnFilterProperty, false));
  201. _tree.FilterPopupStyle = filterstyle;
  202. _tree.FilterChanged += _tree_FilterChanged;
  203. _tree.FilterItemsPopulating += _tree_FilterItemsPopulating;
  204. _tree.FilterLevel = FilterLevel.Extended;
  205. _tree.SelectionForeground = DynamicGridUtils.SelectionForeground;
  206. _tree.SelectionBackground = DynamicGridUtils.SelectionBackground;
  207. _tree.ColumnSizer = TreeColumnSizer.None;
  208. _tree.RowHeight = 30D;
  209. _tree.SetValue(Grid.RowProperty, 0);
  210. _tree.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Visible);
  211. _tree.AllowDraggingRows = false;
  212. _tree.Drop += _tree_Drop;
  213. _tree.DragOver += _tree_DragOver;
  214. _tree.RowDragDropTemplate = TemplateGenerator.CreateDataTemplate(() =>
  215. {
  216. var border = new Border();
  217. border.Width = 100;
  218. border.Height = 100;
  219. border.BorderBrush = new SolidColorBrush(Colors.Firebrick);
  220. border.Background = new SolidColorBrush(Colors.Red);
  221. border.CornerRadius = new CornerRadius(5);
  222. return border;
  223. });
  224. _tree.SizeChanged += _tree_SizeChanged;
  225. }
  226. #region Public Interface
  227. public IEnumerable<CoreRow> GetChildren(Guid id)
  228. {
  229. return Nodes.GetChildren(id).Select(x => MapRow(x.Row)).NotNull();
  230. }
  231. #endregion
  232. #region Input
  233. private CoreRow? GetRowFromIndex(int rowIndex)
  234. {
  235. // Syncfusion has given us the row index, so it also will give us the correct row, after sorting.
  236. // Hence, here we use the syncfusion DataGrid.GetRecordAtRowIndex, which *should* always return a DataRowView.
  237. var row = _tree.GetNodeAtRowIndex(rowIndex);
  238. return MapRow((row.Item as CoreTreeNode)?.Row);
  239. }
  240. private void _tree_CellDoubleTapped(object? sender, TreeGridCellDoubleTappedEventArgs e)
  241. {
  242. _tree.Dispatcher.BeginInvoke(() =>
  243. {
  244. // This needs to happen outside the event handler, because the items source for the tree view might change during this method, and that causes an internal exception in Syncfusion. We need to finish the event before resetting the items source.
  245. Parent.DoubleClickCell(GetRowFromIndex(e.RowColumnIndex.RowIndex), GetColumn(e.RowColumnIndex.ColumnIndex));
  246. });
  247. }
  248. private void _tree_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
  249. {
  250. if (sender != _tree) return;
  251. Parent.HandleKey(e);
  252. }
  253. private void HeaderCell_LeftMouseButtonEvent(object sender, MouseButtonEventArgs e)
  254. {
  255. if (sender is not TreeGridHeaderCell header) return;
  256. var index = _tree.Columns.IndexOf(header.Column);
  257. if (GetColumn(index) is not DynamicColumnBase column)
  258. return;
  259. if(column is DynamicActionColumn dac)
  260. {
  261. Parent.ExecuteActionColumn(dac, null);
  262. }
  263. }
  264. private void _tree_CellTapped(object? sender, TreeGridCellTappedEventArgs e)
  265. {
  266. if (!_tree.IsEnabled)
  267. return;
  268. if (GetColumn(e.RowColumnIndex.ColumnIndex) is not DynamicColumnBase column)
  269. return;
  270. if(e.ChangedButton == MouseButton.Left)
  271. {
  272. if(column is DynamicActionColumn dac)
  273. {
  274. Parent.ExecuteActionColumn(dac, SelectedRows);
  275. }
  276. }
  277. else if(e.ChangedButton == MouseButton.Right)
  278. {
  279. if(column is DynamicMenuColumn dmc)
  280. {
  281. Parent.ExecuteActionColumn(dmc, null);
  282. }
  283. else
  284. {
  285. Parent.OpenColumnMenu(column);
  286. }
  287. }
  288. }
  289. #endregion
  290. #region Selection
  291. public CoreRow[] SelectedRows
  292. {
  293. get
  294. {
  295. return _tree.SelectedItems.OfType<CoreTreeNode>()
  296. .Select(x => GetRow(x)).NotNull().ToArray();
  297. }
  298. set
  299. {
  300. _tree.SelectedItems.Clear();
  301. foreach (var row in value)
  302. {
  303. _tree.SelectedItems.Add(Nodes.Find(row.Get<Guid>(IDColumn.Property)));
  304. }
  305. }
  306. }
  307. private void _tree_SelectionChanged(object? sender, GridSelectionChangedEventArgs e)
  308. {
  309. if(Parent.IsReady && !Parent.IsRefreshing)
  310. {
  311. Parent.SelectItems(SelectedRows);
  312. }
  313. }
  314. private void _tree_SelectionChanging(object? sender, GridSelectionChangingEventArgs e)
  315. {
  316. var cancel = new CancelEventArgs();
  317. Parent.BeforeSelection(cancel);
  318. if (cancel.Cancel)
  319. {
  320. e.Cancel = true;
  321. }
  322. }
  323. #endregion
  324. private void _tree_FilterItemsPopulating(object? sender, Syncfusion.UI.Xaml.TreeGrid.Filtering.TreeGridFilterItemsPopulatingEventArgs e)
  325. {
  326. var col = _tree.Columns.IndexOf(e.Column);
  327. if (GetColumn(col) is DynamicActionColumn dac && dac.Filters is not null)
  328. {
  329. e.ItemsSource = dac.Filters.Select(x => new FilterElement
  330. {
  331. DisplayText = x, ActualValue = x,
  332. IsSelected = dac.SelectedFilters is null || dac.SelectedFilters.Contains(x)
  333. });
  334. }
  335. else if (GetColumn(col) is DynamicGridColumn dgc)
  336. {
  337. var preds = e.Column.FilterPredicates.Select(x => x.FilterValue).ToArray();
  338. var data = Parent.Data.Rows.Select(r => r.Get<String>(dgc.ColumnName)).OrderBy(x=>x);
  339. e.ItemsSource = data.Select(x => new FilterElement()
  340. { DisplayText = x ?? "(Blanks)", ActualValue = x, IsSelected = !preds.Any() || preds.Contains(x) });
  341. }
  342. }
  343. private void _tree_FilterChanged(object? sender, Syncfusion.UI.Xaml.TreeGrid.Filtering.TreeGridFilterChangedEventArgs e)
  344. {
  345. var col = _tree.Columns.IndexOf(e.Column);
  346. if (GetColumn(col) is DynamicActionColumn column)
  347. {
  348. if (e.FilterPredicates != null)
  349. {
  350. var filter = e.FilterPredicates.Select(x => x.FilterValue.ToString()!).ToArray();
  351. bool include = e.FilterPredicates.Any(x => x.FilterType == FilterType.Equals);
  352. column.SelectedFilters = include ? filter : (column.Filters ?? Enumerable.Empty<string>()).Except(filter).ToArray();
  353. }
  354. else
  355. column.SelectedFilters = Array.Empty<string>();
  356. _tree.ClearFilter(e.Column);
  357. //e.FilterPredicates?.Clear();
  358. //e.FilterPredicates?.Add(new FilterPredicate() { PredicateType = PredicateType.Or, FilterBehavior = Syncfusion.Data.FilterBehavior.StringTyped, FilterMode = ColumnFilter.DisplayText, FilterType = Syncfusion.Data.FilterType.NotEquals, FilterValue = "" });
  359. //e.FilterPredicates?.Add(new FilterPredicate() { PredicateType = PredicateType.Or, FilterBehavior = Syncfusion.Data.FilterBehavior.StringTyped, FilterMode = ColumnFilter.DisplayText, FilterType = Syncfusion.Data.FilterType.Equals, FilterValue = "" });
  360. Parent.Refresh(false, false);
  361. }
  362. if (e.FilterPredicates == null)
  363. {
  364. if (FilterPredicates.ContainsKey(e.Column.MappingName))
  365. FilterPredicates.Remove(e.Column.MappingName);
  366. }
  367. else
  368. {
  369. FilterPredicates[e.Column.MappingName] = Serialization.Serialize(e.FilterPredicates, true);
  370. }
  371. Parent.UIFilterChanged(this);
  372. UpdateRecordCount();
  373. }
  374. private CoreRow? GetRow(CoreTreeNode? node)
  375. {
  376. return MapRow(node?.Row);
  377. }
  378. private CoreRow? MapRow(CoreRow? row)
  379. {
  380. if (row is null) return null;
  381. var index = row.Index;
  382. if (index < 0 || index >= Parent.Data.Rows.Count) return null;
  383. return Parent.Data.Rows[row.Index];
  384. }
  385. private void ColumnsMenu_ContextMenuOpening(object sender, RoutedEventArgs e)
  386. {
  387. if (sender is not ContextMenu menu) return;
  388. menu.Items.Clear();
  389. Parent.LoadColumnsMenu(menu);
  390. }
  391. public bool OptionsChanged()
  392. {
  393. ColumnsMenu.Visibility = Parent.HasOption(DynamicGridOption.SelectColumns) ? Visibility.Visible : Visibility.Hidden;
  394. _tree.AllowFiltering = Parent.HasOption(DynamicGridOption.FilterRows);
  395. if (Parent.HasOption(DynamicGridOption.DragSource))
  396. {
  397. if (!_tree.AllowDraggingRows)
  398. {
  399. _tree.AllowDraggingRows = true;
  400. _tree.RowDragDropController.DragStart += RowDragDropController_DragStart;
  401. }
  402. }
  403. else
  404. {
  405. if (_tree.AllowDraggingRows)
  406. {
  407. _tree.AllowDraggingRows = false;
  408. _tree.RowDragDropController.DragStart -= RowDragDropController_DragStart;
  409. }
  410. }
  411. _tree.AllowDrop = Parent.HasOption(DynamicGridOption.DragTarget);
  412. _tree.SelectionMode = Parent.HasOption(DynamicGridOption.MultiSelect) ? GridSelectionMode.Extended : GridSelectionMode.Single;
  413. return false;
  414. }
  415. private void _tree_CellToolTipOpening(object? sender, TreeGridCellToolTipOpeningEventArgs e)
  416. {
  417. if (GetColumn(e.RowColumnIndex.ColumnIndex) is not DynamicActionColumn col)
  418. return;
  419. var toolTip = col.ToolTip;
  420. if (toolTip is null)
  421. return;
  422. var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
  423. e.ToolTip.Template = TemplateGenerator.CreateControlTemplate(
  424. typeof(ToolTip),
  425. () => toolTip.Invoke(col, row)
  426. );
  427. }
  428. #region Sizing
  429. public double RowHeight
  430. {
  431. get => _tree.RowHeight;
  432. set => _tree.RowHeight = value;
  433. }
  434. public double HeaderRowHeight
  435. {
  436. get => _tree.HeaderRowHeight;
  437. set => _tree.HeaderRowHeight = value;
  438. }
  439. private void _tree_SizeChanged(object sender, SizeChangedEventArgs e)
  440. {
  441. CalculateRowHeight();
  442. if (Parent.IsReady && !Parent.IsRefreshing)
  443. ResizeColumns(_tree, e.NewSize.Width - 2, e.NewSize.Height - 2);
  444. }
  445. int IDynamicGridUIComponent<T>.DesiredWidth()
  446. {
  447. return this.DesiredWidth();
  448. }
  449. #endregion
  450. #region Context Menu
  451. private void _tree_ContextMenuOpening(object sender, ContextMenuEventArgs e)
  452. {
  453. _menu.Items.Clear();
  454. if (OnContextMenuOpening is not null)
  455. {
  456. OnContextMenuOpening.Invoke((_tree.SelectedItem as CoreTreeNode)!, _menu);
  457. if(_menu.Items.Count == 0)
  458. {
  459. e.Handled = true;
  460. }
  461. }
  462. else
  463. {
  464. if (Parent.HasOption(DynamicGridOption.AddRows))
  465. {
  466. _menu.AddItem("Add Item", null, (_tree.SelectedItem as CoreTreeNode)!.ID, (id) => DoAddItem(id, true));
  467. }
  468. }
  469. }
  470. #endregion
  471. #region CRUD
  472. protected T DoCreateItem(Guid parent)
  473. {
  474. var result = Parent.CreateItem();
  475. CoreUtils.SetPropertyValue(result, ParentColumn.Property, parent);
  476. return result;
  477. }
  478. protected void DoAddItem(Guid id, bool edit)
  479. {
  480. try
  481. {
  482. var item = DoCreateItem(id);
  483. if (edit)
  484. {
  485. if (Parent.EditItems(new[] { item }))
  486. {
  487. Parent.DoChanged();
  488. Parent.Refresh(false, true);
  489. }
  490. }
  491. else
  492. {
  493. Parent.SaveItem(item);
  494. Parent.DoChanged();
  495. Parent.Refresh(false, true);
  496. }
  497. }
  498. catch (Exception e)
  499. {
  500. MessageWindow.ShowError("An error occurred while adding an item", e);
  501. }
  502. }
  503. #endregion
  504. #region Columns
  505. private readonly List<DynamicColumnBase> ColumnList = new();
  506. private List<DynamicActionColumn> ActionColumns = new();
  507. private readonly Dictionary<string, string> FilterPredicates = new();
  508. private DynamicColumnBase? GetColumn(int index) =>
  509. index >= 0 && index < ColumnList.Count ? ColumnList[index] : null;
  510. private void ApplyFilterStyle(TreeGridColumn column, bool filtering, bool isactioncolumn)
  511. {
  512. var filterstyle = new Style();
  513. if (filtering)
  514. {
  515. filterstyle.Setters.Add(new Setter(Control.BackgroundProperty, DynamicGridUtils.FilterBackground));
  516. column.ImmediateUpdateColumnFilter = true;
  517. column.ColumnFilter = ColumnFilter.DisplayText;
  518. column.AllowBlankFilters = true;
  519. column.AllowSorting = isactioncolumn
  520. ? false
  521. : Parent.CanSort();
  522. }
  523. else
  524. {
  525. filterstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  526. filterstyle.Setters.Add(new Setter(Control.IsEnabledProperty, false));
  527. column.ColumnFilter = ColumnFilter.Value;
  528. column.AllowFiltering = false;
  529. column.AllowSorting = false;
  530. }
  531. }
  532. public class TemplateColumnSelector(DynamicGridTreeUIComponent<T> parent, Func<CoreRow, FrameworkElement> dataTemplate) : DataTemplateSelector
  533. {
  534. public Func<CoreRow, FrameworkElement> DataTemplate { get; init; } = dataTemplate;
  535. public DynamicGridTreeUIComponent<T> Parent { get; init; } = parent;
  536. public override DataTemplate? SelectTemplate(object item, DependencyObject container)
  537. {
  538. if (item is not CoreTreeNode node) return null;
  539. var row = Parent.MapRow(node.Row);
  540. if (row is null) return null;
  541. return TemplateGenerator.CreateDataTemplate(() =>
  542. {
  543. return DataTemplate(row);
  544. });
  545. }
  546. }
  547. private void LoadActionColumns(DynamicActionColumnPosition position)
  548. {
  549. for (var i = 0; i < ActionColumns.Count; i++)
  550. {
  551. var column = ActionColumns[i];
  552. if (column.Position == position)
  553. {
  554. var sColName = $"[_ActionColumn{i}]";
  555. if (column is DynamicImageColumn imgcol)
  556. {
  557. var newcol = new TreeGridTemplateColumn();
  558. newcol.CellTemplateSelector = new TemplateColumnSelector(this, row =>
  559. {
  560. var image = new Image
  561. {
  562. Width = _tree.RowHeight - 8,
  563. Height = _tree.RowHeight - 8,
  564. };
  565. image.SetBinding(Image.SourceProperty, new Binding(sColName));
  566. return image;
  567. });
  568. newcol.AllowEditing = false;
  569. newcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
  570. newcol.Width = column.Width == 0 ? _tree.RowHeight : column.Width;
  571. newcol.Padding = new Thickness(4);
  572. newcol.ColumnSizer = TreeColumnSizer.None;
  573. newcol.HeaderText = column.HeaderText;
  574. ApplyFilterStyle(newcol, false, true);
  575. newcol.ShowToolTip = column.ToolTip != null;
  576. newcol.ShowHeaderToolTip = column.ToolTip != null;
  577. var headstyle = new Style(typeof(TreeGridHeaderCell));
  578. headstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  579. headstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  580. headstyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  581. headstyle.Setters.Add(new EventSetter(Control.MouseLeftButtonUpEvent, new MouseButtonEventHandler(HeaderCell_LeftMouseButtonEvent)));
  582. if (!string.IsNullOrWhiteSpace(column.HeaderText))
  583. {
  584. //headstyle.Setters.Add(new Setter(LayoutTransformProperty, new RotateTransform(270.0F)));
  585. headstyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0.0, 0.0, 0, 0)));
  586. headstyle.Setters.Add(new Setter(Control.MarginProperty, new Thickness(0, 0, 0.75, 0.75)));
  587. if (imgcol.VerticalHeader)
  588. headstyle.Setters.Add(new Setter(Control.TemplateProperty,
  589. Application.Current.Resources["VerticalColumnHeader"] as ControlTemplate));
  590. }
  591. else
  592. {
  593. var image = imgcol.Image?.Invoke(null);
  594. if (image != null)
  595. {
  596. var template = new DataTemplate(typeof(TreeGridHeaderCell));
  597. var border = new FrameworkElementFactory(typeof(Border));
  598. border.SetValue(Border.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro));
  599. border.SetValue(Border.PaddingProperty, new Thickness(4));
  600. border.SetValue(Control.MarginProperty, new Thickness(0, 0, 1, 1));
  601. var img = new FrameworkElementFactory(typeof(Image));
  602. img.SetValue(Image.SourceProperty, image);
  603. border.AppendChild(img);
  604. template.VisualTree = border;
  605. headstyle.Setters.Add(new Setter(TreeGridHeaderCell.PaddingProperty, new Thickness(0)));
  606. headstyle.Setters.Add(new Setter(TreeGridHeaderCell.ContentTemplateProperty, template));
  607. }
  608. }
  609. newcol.HeaderStyle = headstyle;
  610. _tree.Columns.Add(newcol);
  611. ColumnList.Add(column);
  612. }
  613. else if (column is DynamicTextColumn txtCol)
  614. {
  615. var newcol = new TreeGridTextColumn();
  616. newcol.TextWrapping = TextWrapping.NoWrap;
  617. newcol.TextAlignment = txtCol.Alignment == Alignment.NotSet
  618. ? TextAlignment.Left
  619. : txtCol.Alignment == Alignment.BottomLeft || txtCol.Alignment == Alignment.MiddleLeft ||
  620. txtCol.Alignment == Alignment.TopLeft
  621. ? TextAlignment.Left
  622. : txtCol.Alignment == Alignment.BottomCenter || txtCol.Alignment == Alignment.MiddleCenter ||
  623. txtCol.Alignment == Alignment.TopCenter
  624. ? TextAlignment.Center
  625. : TextAlignment.Right;
  626. newcol.AllowEditing = false;
  627. newcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
  628. newcol.MappingName = sColName;
  629. newcol.Width = column.Width;
  630. newcol.ColumnSizer = TreeColumnSizer.None;
  631. newcol.HeaderText = column.HeaderText;
  632. //newcol.AllowFiltering = column.Filters != null && column.Filters.Any();
  633. newcol.AllowSorting = false;
  634. newcol.ShowHeaderToolTip = column.ToolTip != null;
  635. ApplyFilterStyle(newcol, false, true);
  636. var headstyle = new Style(typeof(TreeGridHeaderCell));
  637. headstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  638. headstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  639. headstyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  640. headstyle.Setters.Add(new Setter(Control.MarginProperty, new Thickness(0, -0.75, 0, 0.75)));
  641. headstyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0.75)));
  642. headstyle.Setters.Add(new EventSetter(Control.MouseLeftButtonUpEvent, new MouseButtonEventHandler(HeaderCell_LeftMouseButtonEvent)));
  643. if (txtCol.VerticalHeader)
  644. {
  645. headstyle.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Left));
  646. headstyle.Setters.Add(new Setter(Control.TemplateProperty,
  647. Application.Current.Resources["VerticalColumnHeader"] as ControlTemplate));
  648. }
  649. newcol.HeaderStyle = headstyle;
  650. _tree.Columns.Add(newcol);
  651. ColumnList.Add(column);
  652. }
  653. else if (column is DynamicTemplateColumn tmplCol)
  654. {
  655. var newcol = new TreeGridTemplateColumn();
  656. newcol.CellTemplateSelector = new TemplateColumnSelector(this, tmplCol.Template);
  657. newcol.AllowEditing = false;
  658. newcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
  659. newcol.Width = tmplCol.Width;
  660. newcol.ColumnSizer = TreeColumnSizer.None;
  661. newcol.HeaderText = column.HeaderText;
  662. //newcol.AllowFiltering = false;
  663. newcol.AllowSorting = false;
  664. newcol.ShowToolTip = false;
  665. newcol.ShowHeaderToolTip = false;
  666. ApplyFilterStyle(newcol, false, true);
  667. var headstyle = new Style(typeof(TreeGridHeaderCell));
  668. headstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  669. headstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  670. headstyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  671. headstyle.Setters.Add(new Setter(Control.MarginProperty, new Thickness(0, -0.75, 0, 0.75)));
  672. headstyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0.75)));
  673. headstyle.Setters.Add(new EventSetter(Control.MouseLeftButtonUpEvent, new MouseButtonEventHandler(HeaderCell_LeftMouseButtonEvent)));
  674. newcol.HeaderStyle = headstyle;
  675. _tree.Columns.Add(newcol);
  676. ColumnList.Add(column);
  677. }
  678. }
  679. }
  680. }
  681. private void LoadDataColumns(DynamicGridColumns columns)
  682. {
  683. foreach (var column in columns)
  684. {
  685. if(this.CreateEditorColumn(column, out var newcol, out var prop))
  686. {
  687. //newcol.GetEntity = () => _editingObject.Object;
  688. //newcol.EntityChanged += DoEntityChanged;
  689. var newColumn = newcol.CreateTreeGridColumn();
  690. //newColumn.AllowEditing = newcol.Editable && Parent.IsDirectEditMode();
  691. ApplyFilterStyle(newColumn, newcol.Filtered, false);
  692. var headstyle = new Style(typeof(TreeGridHeaderCell));
  693. headstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  694. headstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  695. headstyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  696. newColumn.HeaderStyle = headstyle;
  697. var cellstyle = new Style();
  698. if (Parent.IsDirectEditMode())
  699. {
  700. if (prop.Editor is null || !prop.Editor.Editable.IsDirectEditable())
  701. {
  702. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  703. new SolidColorBrush(Colors.WhiteSmoke)));
  704. newColumn.AllowEditing = false;
  705. }
  706. else
  707. {
  708. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  709. new SolidColorBrush(Colors.LightYellow)));
  710. newColumn.AllowEditing = true;
  711. }
  712. cellstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  713. newColumn.CellStyle = cellstyle;
  714. }
  715. else
  716. {
  717. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  718. new Binding()
  719. {
  720. Path = new PropertyPath("."), Converter = CellBackgroundConverter,
  721. ConverterParameter = column.ColumnName
  722. }));
  723. cellstyle.Setters.Add(new Setter(Control.ForegroundProperty,
  724. new Binding()
  725. { Converter = CellForegroundConverter, ConverterParameter = column.ColumnName }));
  726. cellstyle.Setters.Add(new Setter(Control.FontSizeProperty,
  727. new Binding()
  728. { Converter = CellFontSizeConverter, ConverterParameter = column.ColumnName }));
  729. cellstyle.Setters.Add(new Setter(Control.FontStyleProperty,
  730. new Binding()
  731. { Converter = CellFontStyleConverter, ConverterParameter = column.ColumnName }));
  732. cellstyle.Setters.Add(new Setter(Control.FontWeightProperty,
  733. new Binding()
  734. { Converter = CellFontWeightConverter, ConverterParameter = column.ColumnName }));
  735. newColumn.CellStyle = cellstyle;
  736. }
  737. _tree.Columns.Add(newColumn);
  738. ColumnList.Add(column);
  739. foreach (var extra in newcol.ExtraColumns)
  740. Parent.AddHiddenColumn(extra);
  741. }
  742. }
  743. }
  744. public void RefreshColumns(DynamicGridColumns columns, DynamicActionColumns actionColumns)
  745. {
  746. _tree.ItemsSource = null;
  747. _tree.Columns.Suspend();
  748. ColumnList.Clear();
  749. _tree.Columns.Clear();
  750. ActionColumns = actionColumns.ToList();
  751. //_tree.Columns.Add(new TreeGridTextColumn()
  752. // {
  753. // MappingName = "Number",
  754. // Width = _shownumbers ? 50 : 0,
  755. // TextAlignment = TextAlignment.Right
  756. // }
  757. //);
  758. LoadActionColumns(DynamicActionColumnPosition.Start);
  759. LoadDataColumns(columns);
  760. LoadActionColumns(DynamicActionColumnPosition.End);
  761. _tree.Columns.Resume();
  762. _tree.RefreshColumns();
  763. foreach (var key in FilterPredicates.Keys.ToArray())
  764. if (_tree.Columns.Any(x => string.Equals(x.MappingName, key)))
  765. {
  766. var predicates = Serialization.Deserialize<List<FilterPredicate>>(FilterPredicates[key]);
  767. foreach (var predicate in predicates)
  768. {
  769. _tree.Columns[key].FilterPredicates.Add(predicate);
  770. }
  771. }
  772. else
  773. {
  774. FilterPredicates.Remove(key);
  775. }
  776. ResizeColumns(_tree, _tree.ActualWidth - 2, _tree.ActualHeight - 2);
  777. }
  778. private void ResizeColumns(SfTreeGrid grid, double width, double height)
  779. {
  780. if (Parent.Data == null || width <= 0)
  781. return;
  782. grid.Dispatcher.BeginInvoke(() =>
  783. {
  784. foreach (var (index, size) in this.CalculateColumnSizes(width))
  785. _tree.Columns[index].Width = Math.Max(0.0F, size);
  786. });
  787. }
  788. #endregion
  789. #region Refresh
  790. public CoreTreeNodes Nodes { get; set; }
  791. private CoreTable? _innerTable;
  792. public void BeforeRefresh()
  793. {
  794. _tree.SelectionForeground = DynamicGridUtils.SelectionForeground;
  795. _tree.SelectionBackground = DynamicGridUtils.SelectionBackground;
  796. }
  797. public void RefreshData(CoreTable data)
  798. {
  799. var nodes = new CoreTreeNodes();
  800. _innerTable = new CoreTable();
  801. _innerTable.LoadColumns(data.Columns);
  802. for (var i = 0; i < ActionColumns.Count; i++)
  803. _innerTable.Columns.Add(
  804. new CoreColumn
  805. {
  806. ColumnName = $"_ActionColumn{i}",
  807. DataType = ActionColumns[i] is DynamicImageColumn
  808. ? typeof(BitmapImage)
  809. : typeof(String)
  810. });
  811. foreach (var row in data.Rows)
  812. {
  813. var newRow = _innerTable.NewRow();
  814. ProcessRow(newRow, row);
  815. _innerTable.Rows.Add(newRow);
  816. var _id = row.Get<Guid>(IDColumn.Property);
  817. var _parent = row.Get<Guid>(ParentColumn.Property);
  818. nodes.Add(_id, _parent, newRow);
  819. }
  820. Nodes = nodes;
  821. _tree.ItemsSource = nodes.Nodes;
  822. CalculateRowHeight();
  823. ResizeColumns(_tree, _tree.ActualWidth - 1, _tree.ActualHeight);
  824. UpdateRecordCount();
  825. }
  826. private void ProcessRow(CoreRow innerRow, CoreRow row)
  827. {
  828. innerRow.LoadValues(row.Values);
  829. for (var i = 0; i < ActionColumns.Count; i++)
  830. {
  831. var ac = ActionColumns[i];
  832. innerRow[$"_ActionColumn{i}"] = ac.Data(row);
  833. }
  834. }
  835. private void CalculateRowHeight()
  836. {
  837. if(Parent.Data != null && Parent.Data.Rows.Count > 0)
  838. {
  839. var contentHeight = _tree.ActualHeight - (_tree.Padding.Top + _tree.Padding.Bottom) - 2; // Two extra pixels of space
  840. var targetHeight = contentHeight / Parent.Data.Rows.Count;
  841. _tree.RowHeight = Math.Max(Math.Min(targetHeight, MaxRowHeight), MinRowHeight);
  842. }
  843. }
  844. private void UpdateRecordCount()
  845. {
  846. var count = _tree.View != null ? _tree.View.Nodes.Count : Parent.Data.Rows.Count;
  847. Parent.UpdateRecordCount(count);
  848. }
  849. #endregion
  850. public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  851. {
  852. if (value.IsNullOrWhiteSpace())
  853. return;
  854. var col = _tree.Columns.FirstOrDefault((x => string.Equals(x.MappingName?.ToUpper(),column?.Replace(".", "_").ToUpper())));
  855. if (col != null)
  856. {
  857. col.FilterPredicates.Add(new FilterPredicate { FilterType = filtertype, FilterValue = value });
  858. }
  859. }
  860. public List<Tuple<string, Func<CoreRow, bool>>> GetFilterPredicates()
  861. {
  862. var list = new List<Tuple<string, Func<CoreRow, bool>>>();
  863. foreach (var column in _tree.Columns)
  864. {
  865. var colIndex = _tree.Columns.IndexOf(column);
  866. var col = ColumnList[colIndex];
  867. if (col is DynamicGridColumn gridColumn)
  868. {
  869. var rowPredicate = DynamicGridGridUIComponentExtension.ConvertColumnPredicates(gridColumn, column.FilterPredicates);
  870. if(rowPredicate is not null)
  871. {
  872. list.Add(new(gridColumn.ColumnName, rowPredicate));
  873. }
  874. }
  875. }
  876. return list;
  877. }
  878. public CoreRow[] GetVisibleRows()
  879. {
  880. return _tree.View?.Nodes.Select(x => MapRow((x.Item as CoreTreeNode)?.Row)).NotNull().ToArray() ?? new CoreRow[] { };
  881. }
  882. public void InvalidateRow(CoreRow row)
  883. {
  884. if (_innerTable is null || row.Index < 0 || row.Index >= _innerTable.Rows.Count) return;
  885. var _innerRow = _innerTable.Rows[row.Index];
  886. ProcessRow(_innerRow, row);
  887. var coreTreeNode = Nodes.Find(_innerRow);
  888. coreTreeNode?.InvalidateData();
  889. }
  890. public void ScrollIntoView(CoreRow row)
  891. {
  892. _tree.ScrollInView(new RowColumnIndex(row.Index + 1, 0));
  893. }
  894. public void UpdateCell(CoreRow row, string column, object? value)
  895. {
  896. throw new NotImplementedException();
  897. }
  898. public void UpdateRow(CoreRow row)
  899. {
  900. throw new NotImplementedException();
  901. }
  902. #region Drag + Drop
  903. private void _tree_DragOver(object sender, DragEventArgs e)
  904. {
  905. Parent.DragOver(sender, e);
  906. }
  907. private void _tree_Drop(object sender, DragEventArgs e)
  908. {
  909. Parent.Drop(sender, e);
  910. }
  911. private void RowDragDropController_DragStart(object? sender, TreeGridRowDragStartEventArgs e)
  912. {
  913. var rows = e.DraggingNodes.Select(node => MapRow((node.Item as CoreTreeNode)?.Row)).NotNull().ToArray();
  914. Parent.DragStart(sender, rows);
  915. }
  916. #endregion
  917. }