DynamicGridTreeUIComponent.cs 37 KB

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