DynamicGridTreeUIComponent.cs 38 KB

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