DynamicGridTreeUIComponent.cs 36 KB

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