DynamicGridTreeUIComponent.cs 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932
  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.Data;
  14. using System.Linq;
  15. using System.Linq.Expressions;
  16. using System.Text;
  17. using System.Threading.Tasks;
  18. using System.Windows;
  19. using System.Windows.Controls;
  20. using System.Windows.Data;
  21. using System.Windows.Input;
  22. using System.Windows.Media;
  23. using System.Windows.Media.Imaging;
  24. using Syncfusion.UI.Xaml.TreeGrid.Filtering;
  25. using Syncfusion.UI.Xaml.TreeGrid.Cells;
  26. using System.Windows.Controls.Primitives;
  27. using NPOI.OpenXmlFormats.Dml;
  28. using System.Windows.Navigation;
  29. using NavigationMode = Syncfusion.UI.Xaml.Grid.NavigationMode;
  30. namespace InABox.DynamicGrid;
  31. public enum DynamicTreeGridLines
  32. {
  33. Both,
  34. Horizontal,
  35. Vertical,
  36. None
  37. }
  38. public enum DynamicTreeGridExpandMode
  39. {
  40. All,
  41. Root,
  42. None
  43. }
  44. public class DynamicGridTreeUIComponent<T, TKey> : IDynamicGridUIComponent<T>, IDynamicGridGridUIComponent<T>
  45. where T : BaseObject, new()
  46. {
  47. private IDynamicGridUIComponentParent<T> _parent;
  48. public IDynamicGridUIComponentParent<T> Parent
  49. {
  50. get => _parent;
  51. set
  52. {
  53. _parent = value;
  54. CellBackgroundConverter = new DynamicGridCellStyleConverter<System.Windows.Media.Brush?>(Parent, GetCellBackground);
  55. CellForegroundConverter = new DynamicGridCellStyleConverter<System.Windows.Media.Brush?>(Parent, GetCellForeground);
  56. CellFontSizeConverter = new DynamicGridCellStyleConverter<double?>(Parent, GetCellFontSize);
  57. CellFontStyleConverter = new DynamicGridCellStyleConverter<System.Windows.FontStyle?>(Parent, GetCellFontStyle);
  58. CellFontWeightConverter = new DynamicGridCellStyleConverter<System.Windows.FontWeight?>(Parent, GetCellFontWeight);
  59. if(IDColumn is not null)
  60. {
  61. Parent.AddHiddenColumn(IDColumn.Property);
  62. }
  63. if(ParentColumn is not null)
  64. {
  65. Parent.AddHiddenColumn(ParentColumn.Property);
  66. }
  67. }
  68. }
  69. private readonly TKey NullKey;
  70. private readonly Func<CoreRow, TKey>? IDKey;
  71. private readonly Func<CoreRow, TKey>? ParentKey;
  72. private readonly Action<T, TKey>? SetParentKey;
  73. private readonly Column<T>? IDColumn;
  74. private readonly Column<T>? ParentColumn;
  75. private ContextMenu _menu;
  76. private SfTreeGrid _tree;
  77. private Grid _summaryRow;
  78. private readonly ContextMenu ColumnsMenu;
  79. public event OnContextMenuOpening<TKey> OnContextMenuOpening;
  80. FrameworkElement IDynamicGridUIComponent<T>.Control => _tree;
  81. private bool _shownumbers = false;
  82. public bool ShowNumbers
  83. {
  84. get => _shownumbers;
  85. set
  86. {
  87. _shownumbers = value;
  88. //_tree.Columns[1].Width = value ? 50 : 0;
  89. }
  90. }
  91. private bool _showHeader = false;
  92. public bool ShowHeader
  93. {
  94. get => _showHeader;
  95. set
  96. {
  97. _showHeader = value;
  98. _tree.HeaderRowHeight = value ? 30 : 0;
  99. }
  100. }
  101. private bool _autoSizeExpander = false;
  102. public bool AutoSizeExpander
  103. {
  104. get => _autoSizeExpander;
  105. set
  106. {
  107. _autoSizeExpander = value;
  108. _tree.AllowAutoSizingExpanderColumn = value;
  109. }
  110. }
  111. private DynamicTreeGridLines _gridLines = DynamicTreeGridLines.Both;
  112. public DynamicTreeGridLines GridLines
  113. {
  114. get => _gridLines;
  115. set
  116. {
  117. _gridLines = value;
  118. _tree.GridLinesVisibility = value switch
  119. {
  120. DynamicTreeGridLines.Both => GridLinesVisibility.Both,
  121. DynamicTreeGridLines.Vertical => GridLinesVisibility.Vertical,
  122. DynamicTreeGridLines.Horizontal => GridLinesVisibility.Horizontal,
  123. _ => GridLinesVisibility.None,
  124. };
  125. }
  126. }
  127. public DynamicTreeGridExpandMode ExpandMode
  128. {
  129. get
  130. {
  131. return _tree.AutoExpandMode switch
  132. {
  133. AutoExpandMode.AllNodesExpanded => DynamicTreeGridExpandMode.All,
  134. AutoExpandMode.RootNodesExpanded => DynamicTreeGridExpandMode.Root,
  135. _ => DynamicTreeGridExpandMode.None,
  136. };
  137. }
  138. set
  139. {
  140. _tree.AutoExpandMode = value switch
  141. {
  142. DynamicTreeGridExpandMode.All => AutoExpandMode.AllNodesExpanded,
  143. DynamicTreeGridExpandMode.Root => AutoExpandMode.RootNodesExpanded,
  144. _ => AutoExpandMode.None
  145. };
  146. }
  147. }
  148. private double minRowHeight = 30D;
  149. private double maxRowHeight = 30D;
  150. public double MinRowHeight
  151. {
  152. get => minRowHeight;
  153. set
  154. {
  155. minRowHeight = value;
  156. CalculateRowHeight();
  157. }
  158. }
  159. public double MaxRowHeight
  160. {
  161. get => maxRowHeight;
  162. set
  163. {
  164. maxRowHeight = value;
  165. CalculateRowHeight();
  166. }
  167. }
  168. #region IDynamicGridGridUIComponent
  169. IList<DynamicColumnBase> IDynamicGridGridUIComponent<T>.ColumnList => ColumnList;
  170. int IDynamicGridGridUIComponent<T>.RowHeight => (int)RowHeight;
  171. #endregion
  172. private DynamicGridCellStyleConverter<System.Windows.Media.Brush?> CellBackgroundConverter;
  173. private DynamicGridCellStyleConverter<System.Windows.Media.Brush?> CellForegroundConverter;
  174. private DynamicGridCellStyleConverter<double?> CellFontSizeConverter;
  175. private DynamicGridCellStyleConverter<System.Windows.FontStyle?> CellFontStyleConverter;
  176. private DynamicGridCellStyleConverter<System.Windows.FontWeight?> CellFontWeightConverter;
  177. public DynamicGridTreeUIComponent(Func<CoreRow, TKey> idKey, Func<CoreRow, TKey> parentKey, TKey nullKey, Action<T, TKey> setParentKey): this()
  178. {
  179. IDKey = idKey;
  180. ParentKey = parentKey;
  181. NullKey = nullKey;
  182. SetParentKey = setParentKey;
  183. }
  184. public DynamicGridTreeUIComponent(Expression<Func<T, TKey>> idColumn, Expression<Func<T, TKey>> parentIDColumn, TKey nullKey): this()
  185. {
  186. IDColumn = new Column<T>(CoreUtils.GetFullPropertyName(idColumn, "."));
  187. ParentColumn = new Column<T>(CoreUtils.GetFullPropertyName(parentIDColumn, "."));
  188. NullKey = nullKey;
  189. }
  190. private DynamicGridTreeUIComponent()
  191. {
  192. ColumnsMenu = new ContextMenu();
  193. ColumnsMenu.Opened += ColumnsMenu_ContextMenuOpening;
  194. _tree = new SfTreeGrid();
  195. _tree.ChildPropertyName = "Children";
  196. //_tree.ParentPropertyName = "Parent";
  197. _tree.AutoGenerateColumns = false;
  198. ExpandMode = DynamicTreeGridExpandMode.All;
  199. //_tree.NodeCollapsing += (o, e) => { e.Cancel = true; };
  200. //_tree.HeaderRowHeight = 0D;
  201. _tree.HeaderRowHeight = 30;
  202. _tree.HeaderContextMenu = ColumnsMenu;
  203. _tree.SelectionChanging += _tree_SelectionChanging;
  204. _tree.SelectionChanged += _tree_SelectionChanged;
  205. _tree.AllowSelectionOnExpanderClick = false;
  206. _tree.AllowAutoSizingExpanderColumn = false;
  207. _tree.CellTapped += _tree_CellTapped;
  208. _tree.CellDoubleTapped += _tree_CellDoubleTapped;
  209. _tree.KeyUp += _tree_KeyUp;
  210. _tree.Loaded += _tree_Loaded;
  211. _tree.CellToolTipOpening += _tree_CellToolTipOpening;
  212. _menu = new ContextMenu();
  213. var additem = new MenuItem() { Header = "Add Child Folder" };
  214. additem.Click += (o, e) => { DoAddItem((_tree.SelectedItem as CoreTreeNode<TKey>)!.ID, true); };
  215. _menu.Items.Add(additem);
  216. _tree.ContextMenuOpening += _tree_ContextMenuOpening;
  217. _tree.ContextMenu = _menu;
  218. _tree.Background = new SolidColorBrush(Colors.DimGray);
  219. var cellStyle = new Style(typeof(TreeGridRowControl));
  220. cellStyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.White)));
  221. _tree.RowStyle = cellStyle;
  222. var filterstyle = new Style(typeof(TreeGridFilterControl));
  223. filterstyle.Setters.Add(new Setter(TreeGridFilterControl.SortOptionVisibilityProperty, Visibility.Collapsed));
  224. filterstyle.Setters.Add(new Setter(TreeGridFilterControl.ImmediateUpdateColumnFilterProperty, false));
  225. _tree.FilterPopupStyle = filterstyle;
  226. _tree.FilterChanging += _tree_FilterChanging;
  227. _tree.FilterChanged += _tree_FilterChanged;
  228. _tree.FilterItemsPopulating += _tree_FilterItemsPopulating;
  229. _tree.FilterLevel = FilterLevel.Extended;
  230. _tree.SelectionForeground = DynamicGridUtils.SelectionForeground;
  231. _tree.SelectionBackground = DynamicGridUtils.SelectionBackground;
  232. _tree.EditTrigger = EditTrigger.OnTap;
  233. _tree.CurrentCellBeginEdit += _tree_CurrentCellBeginEdit;
  234. _tree.CurrentCellEndEdit += _tree_CurrentCellEndEdit;
  235. _tree.CurrentCellDropDownSelectionChanged += _tree_CurrentCellDropDownSelectionChanged;
  236. _tree.PreviewKeyUp += _tree_PreviewKeyUp;
  237. _tree.SelectionController = new TreeGridSelectionControllerExt(_tree, this);
  238. _tree.ColumnSizer = TreeColumnSizer.None;
  239. _tree.RowHeight = 30D;
  240. _tree.SetValue(Grid.RowProperty, 0);
  241. _tree.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, ScrollBarVisibility.Visible);
  242. _tree.AllowDraggingRows = false;
  243. _tree.Drop += _tree_Drop;
  244. _tree.DragOver += _tree_DragOver;
  245. _tree.RowDragDropTemplate = TemplateGenerator.CreateDataTemplate(() =>
  246. {
  247. var border = new Border();
  248. border.Width = 100;
  249. border.Height = 100;
  250. border.BorderBrush = new SolidColorBrush(Colors.Firebrick);
  251. border.Background = new SolidColorBrush(Colors.Red);
  252. border.CornerRadius = new CornerRadius(5);
  253. return border;
  254. });
  255. _tree.SizeChanged += _tree_SizeChanged;
  256. }
  257. private System.Windows.Controls.ScrollChangedEventHandler? _summaryScrollChangedHandler;
  258. private void _tree_Loaded(object sender, RoutedEventArgs e)
  259. {
  260. Application.Current.Dispatcher.BeginInvoke(() =>
  261. {
  262. var firstTime = _summaryRow is null;
  263. if (firstTime)
  264. {
  265. _summaryRow = new Grid();
  266. _summaryRow.Visibility = Nodes is not null && Summaries.Count > 0 ? Visibility.Visible : Visibility.Collapsed;
  267. }
  268. var scroll = _tree.FindChild<ScrollViewer>("PART_ScrollViewer");
  269. if(scroll is not null)
  270. {
  271. var grid = scroll.FindVisualChildren<Grid>(recursive: false).FirstOrDefault();
  272. if(grid is not null)
  273. {
  274. if (firstTime)
  275. {
  276. var row1 = grid.RowDefinitions[0];
  277. var row2 = grid.RowDefinitions[1];
  278. grid.RowDefinitions.Clear();
  279. grid.RowDefinitions.Add(row1);
  280. var rowDef = grid.AddRow(GridUnitType.Auto);
  281. grid.RowDefinitions.Add(row2);
  282. foreach(var child in grid.Children.OfType<UIElement>())
  283. {
  284. var row = Grid.GetRow(child);
  285. if(row >= 1)
  286. {
  287. Grid.SetRow(child, row + 1);
  288. }
  289. else
  290. {
  291. var rowSpan = Grid.GetRowSpan(child);
  292. if(row + rowSpan >= 1 && child is ScrollBar)
  293. {
  294. Grid.SetRowSpan(child, rowSpan + 1);
  295. }
  296. }
  297. }
  298. }
  299. var treeGridPanel = scroll.FindChild<TreeGridPanel>("PART_TreeGridPanel");
  300. var summaryScroll = grid.FindChild<ScrollViewer>("PART_SummaryScroll");
  301. if (summaryScroll is null)
  302. {
  303. summaryScroll = new ScrollViewer
  304. {
  305. VerticalScrollBarVisibility = ScrollBarVisibility.Hidden,
  306. HorizontalScrollBarVisibility = ScrollBarVisibility.Hidden,
  307. Name = "PART_SummaryScroll"
  308. };
  309. summaryScroll.Content = _summaryRow;
  310. if(_summaryScrollChangedHandler is not null)
  311. {
  312. scroll.ScrollChanged -= _summaryScrollChangedHandler;
  313. }
  314. _summaryScrollChangedHandler = (o, e) =>
  315. {
  316. summaryScroll.ScrollToHorizontalOffset(scroll.HorizontalOffset);
  317. };
  318. scroll.ScrollChanged += _summaryScrollChangedHandler;
  319. grid.AddChild(summaryScroll, 1, 0);
  320. }
  321. var transform = new TranslateTransform();
  322. summaryScroll.RenderTransform = transform;
  323. void UpdateSize(double height)
  324. {
  325. var desiredHeight = treeGridPanel.RowHeights.TotalExtent;
  326. if(desiredHeight < height)
  327. {
  328. var diff = height - desiredHeight;
  329. transform.Y = -diff - 1;
  330. }
  331. else
  332. {
  333. transform.Y = 0;
  334. }
  335. }
  336. treeGridPanel.SizeChanged += (o, e) =>
  337. {
  338. UpdateSize(e.NewSize.Height);
  339. };
  340. _tree.FilterChanged += (o, e) =>
  341. {
  342. UpdateSize(treeGridPanel.ActualHeight);
  343. };
  344. UpdateSize(treeGridPanel.ActualHeight);
  345. }
  346. }
  347. RebuildSummaryRow();
  348. });
  349. }
  350. private class TreeGridSelectionControllerExt(SfTreeGrid treeGrid, DynamicGridTreeUIComponent<T, TKey> grid) : TreeGridRowSelectionController(treeGrid)
  351. {
  352. private DynamicGridTreeUIComponent<T, TKey> Grid = grid;
  353. public override bool HandleKeyDown(KeyEventArgs args)
  354. {
  355. if (args.Key == Key.Escape)
  356. {
  357. Grid.CancelEdit();
  358. return false;
  359. }
  360. else
  361. {
  362. return base.HandleKeyDown(args);
  363. }
  364. }
  365. }
  366. #region Public Interface
  367. public IEnumerable<CoreRow> GetChildren(TKey id)
  368. {
  369. return Nodes.GetChildren(id).Select(x => MapRow(x.Row)).NotNull();
  370. }
  371. #endregion
  372. #region Input
  373. private CoreTreeNode<TKey>? GetNodeFromIndex(int rowIndex)
  374. {
  375. // Syncfusion has given us the row index, so it also will give us the correct row, after sorting.
  376. // Hence, here we use the syncfusion DataGrid.GetRecordAtRowIndex, which *should* always return a DataRowView.
  377. var row = _tree.GetNodeAtRowIndex(rowIndex);
  378. return row.Item as CoreTreeNode<TKey>;
  379. }
  380. private CoreRow? GetRowFromIndex(int rowIndex)
  381. {
  382. return MapRow(GetNodeFromIndex(rowIndex)?.Row);
  383. }
  384. private void _tree_CellDoubleTapped(object? sender, TreeGridCellDoubleTappedEventArgs e)
  385. {
  386. _tree.Dispatcher.BeginInvoke(() =>
  387. {
  388. // 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.
  389. Parent.DoubleClickCell(GetRowFromIndex(e.RowColumnIndex.RowIndex), GetColumn(e.RowColumnIndex.ColumnIndex));
  390. });
  391. }
  392. private void _tree_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
  393. {
  394. if (sender != _tree) return;
  395. Parent.HandleKey(e);
  396. }
  397. private void HeaderCell_LeftMouseButtonEvent(object sender, MouseButtonEventArgs e)
  398. {
  399. if (sender is not TreeGridHeaderCell header) return;
  400. var index = _tree.Columns.IndexOf(header.Column);
  401. if (GetColumn(index) is not DynamicColumnBase column)
  402. return;
  403. if(column is DynamicActionColumn dac)
  404. {
  405. Parent.ExecuteActionColumn(dac, null);
  406. }
  407. }
  408. private void _tree_CellTapped(object? sender, TreeGridCellTappedEventArgs e)
  409. {
  410. if (!_tree.IsEnabled)
  411. return;
  412. if (GetColumn(e.RowColumnIndex.ColumnIndex) is not DynamicColumnBase column)
  413. return;
  414. if(e.ChangedButton == MouseButton.Left)
  415. {
  416. if(column is DynamicActionColumn dac)
  417. {
  418. Parent.ExecuteActionColumn(dac, SelectedRows);
  419. }
  420. }
  421. else if(e.ChangedButton == MouseButton.Right)
  422. {
  423. if(column is DynamicMenuColumn dmc)
  424. {
  425. Parent.ExecuteActionColumn(dmc, null);
  426. }
  427. else
  428. {
  429. Parent.OpenColumnMenu(column);
  430. }
  431. }
  432. }
  433. #endregion
  434. #region Selection
  435. public CoreRow[] SelectedRows
  436. {
  437. get
  438. {
  439. return _tree.SelectedItems.OfType<CoreTreeNode<TKey>>()
  440. .Select(x => GetRow(x)).NotNull().ToArray();
  441. }
  442. set
  443. {
  444. _tree.SelectedItems.Clear();
  445. foreach (var row in value)
  446. {
  447. _tree.SelectedItems.Add(Nodes.Find(GetIDKey(row)));
  448. }
  449. }
  450. }
  451. private void _tree_SelectionChanged(object? sender, GridSelectionChangedEventArgs e)
  452. {
  453. if(Parent.IsReady && !Parent.IsRefreshing)
  454. {
  455. Parent.SelectItems(SelectedRows);
  456. }
  457. }
  458. private void _tree_SelectionChanging(object? sender, GridSelectionChangingEventArgs e)
  459. {
  460. var cancel = new CancelEventArgs();
  461. Parent.BeforeSelection(cancel);
  462. if (cancel.Cancel)
  463. {
  464. e.Cancel = true;
  465. }
  466. }
  467. #endregion
  468. #region FilterUI
  469. private void _tree_FilterItemsPopulating(object? sender, Syncfusion.UI.Xaml.TreeGrid.Filtering.TreeGridFilterItemsPopulatingEventArgs e)
  470. {
  471. var colIdx = _tree.Columns.IndexOf(e.Column);
  472. var column = GetColumn(colIdx);
  473. if(column is not null)
  474. {
  475. var filterItems = Parent.GetColumnFilterItems(column);
  476. if(filterItems is not null)
  477. {
  478. e.ItemsSource = filterItems.Select(x => new FilterElement
  479. {
  480. DisplayText = x, ActualValue = x
  481. });
  482. }
  483. else if (column is DynamicActionColumn dac && dac.Filters is not null)
  484. {
  485. e.ItemsSource = dac.Filters.Select(x => new FilterElement
  486. {
  487. DisplayText = x, ActualValue = x,
  488. IsSelected = (dac.SelectedFilters is null || dac.SelectedFilters.Contains(x))
  489. && (dac.ExcludeFilters is null || dac.ExcludeFilters.Contains(x))
  490. });
  491. }
  492. else if (column is DynamicGridColumn dgc)
  493. {
  494. var preds = e.Column.FilterPredicates.Select(x => x.FilterValue).ToArray();
  495. var data = Parent.Data.Rows.Select(r => r.Get<String>(dgc.ColumnName)).OrderBy(x=>x);
  496. e.ItemsSource = data.Select(x => new FilterElement()
  497. { DisplayText = x ?? "(Blanks)", ActualValue = x, IsSelected = preds.Length == 0 || preds.Contains(x) });
  498. }
  499. }
  500. }
  501. private void _tree_FilterChanging(object? sender, TreeGridFilterChangingEventArgs e)
  502. {
  503. var col = GetColumn(_tree.Columns.IndexOf(e.Column)) as DynamicActionColumn;
  504. if (col?.GetFilterExpression != null)
  505. {
  506. col.SetFilters(e.FilterPredicates);
  507. var view = (_tree.ItemsSource as DataTable)?.DefaultView;
  508. view.ApplyFilters(ColumnList.OfType<DynamicActionColumn>());
  509. e.Handled = true;
  510. }
  511. }
  512. private void _tree_FilterChanged(object? sender, TreeGridFilterChangedEventArgs e)
  513. {
  514. var col = _tree.Columns.IndexOf(e.Column);
  515. if (GetColumn(col) is DynamicActionColumn column)
  516. {
  517. column.SetFilters(e.FilterPredicates);
  518. _tree.ClearFilter(e.Column);
  519. Parent.Refresh(false, false);
  520. }
  521. if (e.FilterPredicates == null)
  522. {
  523. if (FilterPredicates.ContainsKey(e.Column.MappingName))
  524. FilterPredicates.Remove(e.Column.MappingName);
  525. }
  526. else
  527. {
  528. FilterPredicates[e.Column.MappingName] = Serialization.Serialize(e.FilterPredicates, true);
  529. }
  530. Parent.UIFilterChanged(this);
  531. UpdateRecordCount();
  532. CalculateSummaries();
  533. }
  534. public void AddVisualFilter(string column, string value, FilterType filtertype = FilterType.Contains)
  535. {
  536. if (value.IsNullOrWhiteSpace())
  537. return;
  538. var col = _tree.Columns.FirstOrDefault((x => string.Equals(x.MappingName?.ToUpper(),column?.Replace(".", "_").ToUpper())));
  539. if (col != null)
  540. {
  541. col.FilterPredicates.Add(new FilterPredicate { FilterType = filtertype, FilterValue = value });
  542. }
  543. }
  544. public List<Tuple<string, Func<CoreRow, bool>>> GetFilterPredicates()
  545. {
  546. var list = new List<Tuple<string, Func<CoreRow, bool>>>();
  547. foreach (var column in _tree.Columns)
  548. {
  549. var colIndex = _tree.Columns.IndexOf(column);
  550. var col = ColumnList[colIndex];
  551. if (col is DynamicGridColumn gridColumn)
  552. {
  553. var rowPredicate = DynamicGridGridUIComponentExtension.ConvertColumnPredicates(gridColumn, column.FilterPredicates);
  554. if(rowPredicate is not null)
  555. {
  556. list.Add(new(gridColumn.ColumnName, rowPredicate));
  557. }
  558. }
  559. else if(col is DynamicActionColumn dac && dac.FilterRecord is not null)
  560. {
  561. if(dac.SelectedFilters is not null && dac.SelectedFilters.Length > 0)
  562. {
  563. list.Add(new(column.MappingName, (row) => dac.FilterRecord(row, dac.SelectedFilters)));
  564. }
  565. if(dac.ExcludeFilters is not null && dac.ExcludeFilters.Length > 0)
  566. {
  567. list.Add(new(column.MappingName, (row) => !dac.FilterRecord(row, dac.ExcludeFilters)));
  568. }
  569. }
  570. }
  571. return list;
  572. }
  573. #endregion
  574. private void ColumnsMenu_ContextMenuOpening(object sender, RoutedEventArgs e)
  575. {
  576. if (sender is not ContextMenu menu) return;
  577. menu.Items.Clear();
  578. Parent.LoadColumnsMenu(menu);
  579. }
  580. public bool OptionsChanged()
  581. {
  582. ColumnsMenu.Visibility = Parent.Options.SelectColumns ? Visibility.Visible : Visibility.Hidden;
  583. var allowEditing = Parent.IsDirectEditMode();
  584. var reloadColumns = false;
  585. if (_tree.AllowEditing != allowEditing)
  586. {
  587. _tree.NavigationMode = allowEditing ? NavigationMode.Cell : NavigationMode.Row;
  588. _tree.AllowEditing = allowEditing;
  589. reloadColumns = true;
  590. }
  591. _tree.AllowFiltering = Parent.Options.FilterRows;
  592. if (Parent.Options.DragSource)
  593. {
  594. if (!_tree.AllowDraggingRows)
  595. {
  596. _tree.AllowDraggingRows = true;
  597. _tree.RowDragDropController.DragStart += RowDragDropController_DragStart;
  598. }
  599. }
  600. else
  601. {
  602. if (_tree.AllowDraggingRows)
  603. {
  604. _tree.AllowDraggingRows = false;
  605. _tree.RowDragDropController.DragStart -= RowDragDropController_DragStart;
  606. }
  607. }
  608. _tree.AllowDrop = Parent.Options.DragTarget;
  609. _tree.SelectionMode = Parent.Options.MultiSelect ? GridSelectionMode.Extended : GridSelectionMode.Single;
  610. return reloadColumns;
  611. }
  612. private void _tree_CellToolTipOpening(object? sender, TreeGridCellToolTipOpeningEventArgs e)
  613. {
  614. if (GetColumn(e.RowColumnIndex.ColumnIndex) is not DynamicActionColumn col)
  615. return;
  616. var toolTip = col.ToolTip;
  617. if (toolTip is null)
  618. return;
  619. var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
  620. e.ToolTip.Template = TemplateGenerator.CreateControlTemplate(
  621. typeof(ToolTip),
  622. () => toolTip.Invoke(col, row)
  623. );
  624. }
  625. #region Styles
  626. protected virtual Brush? GetCellBackground(CoreRow row, DynamicColumnBase column) => null;
  627. protected virtual Brush? GetCellForeground(CoreRow row, DynamicColumnBase column) => null;
  628. protected virtual double? GetCellFontSize(CoreRow row, DynamicColumnBase column) => null;
  629. protected virtual FontStyle? GetCellFontStyle(CoreRow row, DynamicColumnBase column) => null;
  630. protected virtual FontWeight? GetCellFontWeight(CoreRow row, DynamicColumnBase column) => null;
  631. protected virtual Brush? GetCellSelectionForegroundBrush() => DynamicGridUtils.SelectionForeground;
  632. protected virtual Brush? GetCellSelectionBackgroundBrush() => DynamicGridUtils.SelectionBackground;
  633. protected virtual Style GetHeaderCellStyle(DynamicColumnBase column)
  634. {
  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. if(column is DynamicActionColumn actionColumn)
  640. {
  641. headStyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0.0)));
  642. headStyle.Setters.Add(new Setter(Control.MarginProperty, new Thickness(0, 0, 1, 1)));
  643. if(column is DynamicImageColumn imgCol)
  644. {
  645. if (imgCol.HeaderText.IsNullOrWhiteSpace())
  646. {
  647. var image = imgCol.Image?.Invoke(null);
  648. if (image != null)
  649. {
  650. var template = new ControlTemplate(typeof(TreeGridHeaderCell));
  651. var border = new FrameworkElementFactory(typeof(Border));
  652. border.SetValue(Border.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro));
  653. border.SetValue(Border.PaddingProperty, new Thickness(4));
  654. border.Name = "PART_HeaderCellBorder";
  655. var img = new FrameworkElementFactory(typeof(Image));
  656. img.SetValue(Image.SourceProperty, image);
  657. border.AppendChild(img);
  658. template.VisualTree = border;
  659. headStyle.Setters.Add(new Setter(Control.TemplateProperty, template));
  660. }
  661. }
  662. }
  663. if (actionColumn.VerticalHeader && !actionColumn.HeaderText.IsNullOrWhiteSpace())
  664. {
  665. headStyle.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Left));
  666. headStyle.Setters.Add(new Setter(Control.TemplateProperty,
  667. Application.Current.Resources["VerticalColumnHeader"] as ControlTemplate));
  668. }
  669. }
  670. return headStyle;
  671. }
  672. protected virtual Style GetSummaryCellStyle(DynamicColumnBase column)
  673. {
  674. var style = new Style(typeof(SummaryCellControl));
  675. style.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  676. style.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  677. if(column is DynamicGridColumn gridColumn)
  678. {
  679. style.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty,
  680. column != null ? gridColumn.HorizontalAlignment(typeof(double)) : HorizontalAlignment.Right));
  681. }
  682. else if(column is DynamicTextColumn textColumn)
  683. {
  684. style.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, textColumn.Alignment.HorizontalAlignment(typeof(string))));
  685. }
  686. else
  687. {
  688. style.Setters.Add(new Setter(Control.HorizontalContentAlignmentProperty, HorizontalAlignment.Right));
  689. }
  690. style.Setters.Add(new Setter(Control.VerticalContentAlignmentProperty, VerticalAlignment.Center));
  691. style.Setters.Add(new Setter(Control.BorderBrushProperty, new SolidColorBrush(Colors.Gray)));
  692. style.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0, 0.75, 0.75, 0.0)));
  693. style.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  694. style.Setters.Add(new Setter(Control.FontWeightProperty, FontWeights.DemiBold));
  695. style.Setters.Add(new Setter(Control.PaddingProperty, new Thickness(4)));
  696. return style;
  697. }
  698. #endregion
  699. #region Sizing
  700. public double RowHeight
  701. {
  702. get => _tree.RowHeight;
  703. set => _tree.RowHeight = value;
  704. }
  705. public double HeaderRowHeight
  706. {
  707. get => _tree.HeaderRowHeight;
  708. set => _tree.HeaderRowHeight = value;
  709. }
  710. private void _tree_SizeChanged(object sender, SizeChangedEventArgs e)
  711. {
  712. CalculateRowHeight();
  713. if (Parent.IsReady && !Parent.IsRefreshing)
  714. ResizeColumns(_tree, e.NewSize.Width - 2, e.NewSize.Height - 2);
  715. }
  716. int IDynamicGridUIComponent<T>.DesiredWidth()
  717. {
  718. return this.DesiredWidth();
  719. }
  720. #endregion
  721. #region Context Menu
  722. private void _tree_ContextMenuOpening(object sender, ContextMenuEventArgs e)
  723. {
  724. _menu.Items.Clear();
  725. if (OnContextMenuOpening is not null)
  726. {
  727. OnContextMenuOpening.Invoke((_tree.SelectedItem as CoreTreeNode<TKey>)!, _menu);
  728. if(_menu.Items.Count == 0)
  729. {
  730. e.Handled = true;
  731. }
  732. }
  733. else
  734. {
  735. if (Parent.Options.AddRows)
  736. {
  737. _menu.AddItem("Add Item", null, (_tree.SelectedItem as CoreTreeNode<TKey>)!.ID, (id) => DoAddItem(id, true));
  738. }
  739. }
  740. }
  741. #endregion
  742. #region CRUD
  743. protected T DoCreateItem(TKey parent)
  744. {
  745. var result = Parent.CreateItem();
  746. SetParent(result, parent);
  747. return result;
  748. }
  749. protected void DoAddItem(TKey id, bool edit)
  750. {
  751. try
  752. {
  753. var item = DoCreateItem(id);
  754. if (edit)
  755. {
  756. if (Parent.EditItems(new[] { item }))
  757. {
  758. Parent.DoChanged();
  759. Parent.Refresh(false, true);
  760. }
  761. }
  762. else
  763. {
  764. Parent.SaveItem(item);
  765. Parent.DoChanged();
  766. Parent.Refresh(false, true);
  767. }
  768. }
  769. catch (Exception e)
  770. {
  771. MessageWindow.ShowError("An error occurred while adding an item", e);
  772. }
  773. }
  774. #endregion
  775. #region Rows
  776. private TKey GetIDKey(CoreRow row)
  777. {
  778. if(IDColumn is not null)
  779. {
  780. return row.Get<TKey>(IDColumn.Property);
  781. }
  782. else if(IDKey is not null)
  783. {
  784. return IDKey(row);
  785. }
  786. else
  787. {
  788. return NullKey;
  789. }
  790. }
  791. private TKey GetParentKey(CoreRow row)
  792. {
  793. if(ParentColumn is not null)
  794. {
  795. return row.Get<TKey>(ParentColumn.Property);
  796. }
  797. else if(ParentKey is not null)
  798. {
  799. return ParentKey(row);
  800. }
  801. else
  802. {
  803. return NullKey;
  804. }
  805. }
  806. private void SetParent(T obj, TKey key)
  807. {
  808. if(ParentColumn is not null)
  809. {
  810. ParentColumn.PropertyDefinition.Setter()(obj, key);
  811. }
  812. else if(SetParentKey is not null)
  813. {
  814. SetParentKey(obj, key);
  815. }
  816. }
  817. private CoreRow? GetRow(CoreTreeNode<TKey>? node)
  818. {
  819. return MapRow(node?.Row);
  820. }
  821. private CoreRow? MapRow(CoreRow? row)
  822. {
  823. if (row is null) return null;
  824. var index = row.Index;
  825. if (index < 0 || index >= Parent.Data.Rows.Count) return null;
  826. return Parent.Data.Rows[row.Index];
  827. }
  828. private CoreTreeNode<TKey>? GetNode(CoreRow row)
  829. {
  830. if (_innerTable is null || row.Index < 0 || row.Index >= _innerTable.Rows.Count) return null;
  831. var _innerRow = _innerTable.Rows[row.Index];
  832. var node = Nodes.Find(_innerRow);
  833. return node;
  834. }
  835. public CoreRow[] GetVisibleRows()
  836. {
  837. return _tree.View?.Nodes.Select(x => MapRow((x.Item as CoreTreeNode<TKey>)?.Row)).NotNull().ToArray() ?? new CoreRow[] { };
  838. }
  839. #endregion
  840. #region Columns
  841. private class StackedHeaderRenderer : TreeGridStackedHeaderCellRenderer
  842. {
  843. private Style Style;
  844. public StackedHeaderRenderer()
  845. {
  846. var headstyle = new Style(typeof(TreeGridStackedHeaderCell));
  847. headstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  848. headstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  849. headstyle.Setters.Add(new Setter(Control.FontSizeProperty, 12D));
  850. headstyle.Setters.Add(new Setter(Control.BorderThicknessProperty, new Thickness(0.0, 0.0, 0, 0)));
  851. headstyle.Setters.Add(new Setter(Control.MarginProperty, new Thickness(0, 0, 1, 1)));
  852. Style = headstyle;
  853. }
  854. public override void OnInitializeEditElement(TreeDataColumnBase dataColumn, TreeGridStackedHeaderCell uiElement, object dataContext)
  855. {
  856. uiElement.Style = Style;
  857. base.OnInitializeEditElement(dataColumn, uiElement, dataContext);
  858. }
  859. }
  860. private readonly List<DynamicColumnBase> ColumnList = new();
  861. private List<DynamicActionColumn> ActionColumns = new();
  862. private List<Summary> Summaries = new();
  863. private readonly Dictionary<string, string> FilterPredicates = new();
  864. private DynamicColumnBase? GetColumn(int index) =>
  865. index >= 0 && index < ColumnList.Count ? ColumnList[index] : null;
  866. private void ApplyFilterStyle(TreeGridColumn column, bool filtering, bool isactioncolumn)
  867. {
  868. var filterstyle = new Style();
  869. if (filtering)
  870. {
  871. filterstyle.Setters.Add(new Setter(Control.BackgroundProperty, DynamicGridUtils.FilterBackground));
  872. column.ImmediateUpdateColumnFilter = true;
  873. column.ColumnFilter = ColumnFilter.DisplayText;
  874. column.AllowBlankFilters = true;
  875. column.AllowSorting = isactioncolumn
  876. ? false
  877. : Parent.CanSort();
  878. }
  879. else
  880. {
  881. filterstyle.Setters.Add(new Setter(Control.BackgroundProperty, new SolidColorBrush(Colors.Gainsboro)));
  882. filterstyle.Setters.Add(new Setter(Control.IsEnabledProperty, false));
  883. column.ColumnFilter = ColumnFilter.Value;
  884. column.AllowFiltering = false;
  885. column.AllowSorting = false;
  886. }
  887. }
  888. public class TemplateColumnSelector(DynamicGridTreeUIComponent<T, TKey> parent, Func<CoreRow, FrameworkElement?> dataTemplate) : DataTemplateSelector
  889. {
  890. public Func<CoreRow, FrameworkElement?> DataTemplate { get; init; } = dataTemplate;
  891. public DynamicGridTreeUIComponent<T, TKey> Parent { get; init; } = parent;
  892. public override DataTemplate? SelectTemplate(object item, DependencyObject container)
  893. {
  894. if (item is not CoreTreeNode<TKey> node) return null;
  895. var row = Parent.MapRow(node.Row);
  896. if (row is null) return null;
  897. return TemplateGenerator.CreateDataTemplate(() =>
  898. {
  899. return DataTemplate(row);
  900. });
  901. }
  902. }
  903. private void LoadActionColumn(DynamicActionColumn column)
  904. {
  905. var i = ActionColumns.Count;
  906. var sColName = $"[_ActionColumn{i}]";
  907. ActionColumns.Add(column);
  908. var summary = column.Summary();
  909. if(summary is not null)
  910. {
  911. Summaries.Add(new(column, summary, null, null));
  912. }
  913. if (column is DynamicImageColumn imgcol)
  914. {
  915. var newcol = new TreeGridTemplateColumn();
  916. newcol.CellTemplateSelector = new TemplateColumnSelector(this, row =>
  917. {
  918. var image = new Image
  919. {
  920. Width = _tree.RowHeight - 8,
  921. Height = _tree.RowHeight - 8,
  922. };
  923. image.SetBinding(Image.SourceProperty, new Binding(sColName));
  924. return image;
  925. });
  926. newcol.AllowEditing = false;
  927. newcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
  928. newcol.Width = column.Width == 0 ? _tree.RowHeight : column.Width;
  929. newcol.Padding = new Thickness(4);
  930. newcol.ColumnSizer = TreeColumnSizer.None;
  931. newcol.HeaderText = column.HeaderText;
  932. newcol.MappingName = sColName;
  933. ApplyFilterStyle(newcol, false, true);
  934. newcol.ShowToolTip = column.ToolTip != null;
  935. newcol.ShowHeaderToolTip = column.ToolTip != null;
  936. var headstyle = GetHeaderCellStyle(column);
  937. headstyle.Setters.Add(new EventSetter(Control.MouseLeftButtonUpEvent, new MouseButtonEventHandler(HeaderCell_LeftMouseButtonEvent)));
  938. newcol.HeaderStyle = headstyle;
  939. _tree.Columns.Add(newcol);
  940. ColumnList.Add(column);
  941. }
  942. else if (column is DynamicTextColumn txtCol)
  943. {
  944. var newcol = new TreeGridTextColumn();
  945. newcol.TextWrapping = TextWrapping.NoWrap;
  946. newcol.TextAlignment = txtCol.Alignment.TextAlignment(typeof(string));
  947. newcol.AllowEditing = false;
  948. newcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
  949. newcol.MappingName = sColName;
  950. newcol.Width = column.Width;
  951. newcol.ColumnSizer = TreeColumnSizer.None;
  952. newcol.HeaderText = column.HeaderText;
  953. //newcol.AllowFiltering = column.Filters != null && column.Filters.Any();
  954. newcol.AllowSorting = false;
  955. newcol.ShowHeaderToolTip = column.ToolTip != null;
  956. ApplyFilterStyle(newcol, false, true);
  957. var headstyle = GetHeaderCellStyle(column);
  958. headstyle.Setters.Add(new EventSetter(Control.MouseLeftButtonUpEvent, new MouseButtonEventHandler(HeaderCell_LeftMouseButtonEvent)));
  959. newcol.HeaderStyle = headstyle;
  960. _tree.Columns.Add(newcol);
  961. ColumnList.Add(column);
  962. }
  963. else if (column is DynamicTemplateColumn tmplCol)
  964. {
  965. var newcol = new TreeGridTemplateColumn();
  966. newcol.CellTemplateSelector = new TemplateColumnSelector(this, tmplCol.Template);
  967. newcol.AllowEditing = false;
  968. newcol.UpdateTrigger = UpdateSourceTrigger.PropertyChanged;
  969. newcol.Width = tmplCol.Width;
  970. newcol.ColumnSizer = TreeColumnSizer.None;
  971. newcol.HeaderText = column.HeaderText;
  972. //newcol.AllowFiltering = false;
  973. newcol.AllowSorting = false;
  974. newcol.ShowToolTip = false;
  975. newcol.ShowHeaderToolTip = false;
  976. newcol.MappingName = sColName;
  977. ApplyFilterStyle(newcol, false, true);
  978. var headstyle = GetHeaderCellStyle(column);
  979. headstyle.Setters.Add(new EventSetter(Control.MouseLeftButtonUpEvent, new MouseButtonEventHandler(HeaderCell_LeftMouseButtonEvent)));
  980. newcol.HeaderStyle = headstyle;
  981. _tree.Columns.Add(newcol);
  982. ColumnList.Add(column);
  983. }
  984. }
  985. private void LoadDataColumn(DynamicGridColumn column)
  986. {
  987. if(this.CreateEditorColumn(column, out var newcol, out var prop))
  988. {
  989. newcol.GetEntity = () => _editingObject?.Object;
  990. newcol.EntityChanged += DoEntityChanged;
  991. var newColumn = newcol.CreateTreeGridColumn();
  992. var summary = newcol.Summary();
  993. if(summary is not null)
  994. {
  995. Summaries.Add(new(column, summary, null, null));
  996. }
  997. ApplyFilterStyle(newColumn, newcol.Filtered, false);
  998. newColumn.HeaderStyle = GetHeaderCellStyle(column);
  999. var cellstyle = new Style();
  1000. if (Parent.IsDirectEditMode())
  1001. {
  1002. var editor = Parent.CustomiseEditor(column, column.Editor);
  1003. if (editor is null || !editor.Editable.IsDirectEditable())
  1004. {
  1005. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  1006. new SolidColorBrush(Colors.WhiteSmoke)));
  1007. newColumn.AllowEditing = false;
  1008. }
  1009. else
  1010. {
  1011. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  1012. new SolidColorBrush(Colors.LightYellow)));
  1013. newColumn.AllowEditing = true;
  1014. }
  1015. cellstyle.Setters.Add(new Setter(Control.ForegroundProperty, new SolidColorBrush(Colors.Black)));
  1016. newColumn.CellStyle = cellstyle;
  1017. }
  1018. else
  1019. {
  1020. cellstyle.Setters.Add(new Setter(Control.BackgroundProperty,
  1021. new Binding()
  1022. {
  1023. Path = new PropertyPath("."), Converter = CellBackgroundConverter,
  1024. ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
  1025. }));
  1026. cellstyle.Setters.Add(new Setter(Control.ForegroundProperty,
  1027. new Binding()
  1028. {
  1029. Converter = CellForegroundConverter,
  1030. ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
  1031. }));
  1032. cellstyle.Setters.Add(new Setter(Control.FontSizeProperty,
  1033. new Binding()
  1034. {
  1035. Converter = CellFontSizeConverter,
  1036. ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
  1037. }));
  1038. cellstyle.Setters.Add(new Setter(Control.FontStyleProperty,
  1039. new Binding()
  1040. {
  1041. Converter = CellFontStyleConverter,
  1042. ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
  1043. }));
  1044. cellstyle.Setters.Add(new Setter(Control.FontWeightProperty,
  1045. new Binding()
  1046. {
  1047. Converter = CellFontWeightConverter,
  1048. ConverterParameter = new DynamicGridCellStyleParameters(column,DependencyProperty.UnsetValue)
  1049. }));
  1050. newColumn.CellStyle = cellstyle;
  1051. }
  1052. _tree.Columns.Add(newColumn);
  1053. ColumnList.Add(column);
  1054. foreach (var extra in newcol.ExtraColumns)
  1055. Parent.AddHiddenColumn(extra);
  1056. }
  1057. }
  1058. private void LoadStackedHeaders(DynamicGridColumnGroupings groupings)
  1059. {
  1060. _tree.StackedHeaderRows.Clear();
  1061. foreach(var grouping in groupings)
  1062. {
  1063. var row = new StackedHeaderRow();
  1064. var i = 0;
  1065. foreach(var group in grouping.Groups)
  1066. {
  1067. var start = Math.Max(i, ColumnList.IndexOf(group.StartColumn));
  1068. var end = Math.Max(start, ColumnList.IndexOf(group.EndColumn));
  1069. if(end < start)
  1070. {
  1071. i = end + 1;
  1072. continue;
  1073. }
  1074. var cols = Enumerable.Range(start, end - start + 1).Select(i => _tree.Columns[i]).ToArray();
  1075. var stackedColumn = new StackedColumn
  1076. {
  1077. HeaderText = group.Header,
  1078. ChildColumns = string.Join(',', cols.Select(x => x.MappingName))
  1079. };
  1080. row.StackedColumns.Add(stackedColumn);
  1081. i = end + 1;
  1082. }
  1083. _tree.StackedHeaderRows.Add(row);
  1084. }
  1085. if(groupings.Count > 0)
  1086. {
  1087. _tree.CellRenderers.Remove("StackedHeader");
  1088. _tree.CellRenderers.Add("StackedHeader", new StackedHeaderRenderer());
  1089. }
  1090. }
  1091. public void RefreshColumns(IEnumerable<DynamicColumnBase> columns, DynamicGridColumnGroupings groupings)
  1092. {
  1093. _tree.ItemsSource = null;
  1094. _tree.Columns.Suspend();
  1095. ColumnList.Clear();
  1096. _tree.Columns.Clear();
  1097. Summaries.Clear();
  1098. ActionColumns.Clear();
  1099. foreach(var column in columns)
  1100. {
  1101. if(column is DynamicActionColumn ac)
  1102. {
  1103. LoadActionColumn(ac);
  1104. }
  1105. else if(column is DynamicGridColumn gc)
  1106. {
  1107. LoadDataColumn(gc);
  1108. }
  1109. }
  1110. LoadStackedHeaders(groupings);
  1111. _tree.Columns.Resume();
  1112. _tree.RefreshColumns();
  1113. foreach (var key in FilterPredicates.Keys.ToArray())
  1114. if (_tree.Columns.Any(x => string.Equals(x.MappingName, key)))
  1115. {
  1116. var predicates = Serialization.Deserialize<List<FilterPredicate>>(FilterPredicates[key]);
  1117. foreach (var predicate in predicates)
  1118. {
  1119. _tree.Columns[key].FilterPredicates.Add(predicate);
  1120. }
  1121. }
  1122. else
  1123. {
  1124. FilterPredicates.Remove(key);
  1125. }
  1126. ResizeColumns(_tree, _tree.ActualWidth - 2, _tree.ActualHeight - 2);
  1127. }
  1128. private void ResizeColumns(SfTreeGrid grid, double width, double height)
  1129. {
  1130. if (Parent.Data == null || width <= 0)
  1131. return;
  1132. grid.Dispatcher.BeginInvoke(() =>
  1133. {
  1134. foreach (var (index, size) in this.CalculateColumnSizes(width))
  1135. {
  1136. var colSize = Math.Max(0.0F, size);
  1137. _tree.Columns[index].Width = colSize;
  1138. }
  1139. RebuildSummaryRow();
  1140. });
  1141. }
  1142. #endregion
  1143. #region Summary
  1144. private class Summary(DynamicColumnBase column, IDynamicGridSummary summary, SummaryCellControl? control, object? data)
  1145. {
  1146. public DynamicColumnBase Column { get; set; } = column;
  1147. public IDynamicGridSummary SummaryDefinition { get; set; } = summary;
  1148. public SummaryCellControl? Control { get; set; } = control;
  1149. public object? Data { get; set; } = data;
  1150. }
  1151. protected class SummaryCellControl : ContentControl
  1152. {
  1153. public SummaryCellControl()
  1154. {
  1155. var template = new ControlTemplate(typeof(ContentControl));
  1156. var factory = new FrameworkElementFactory(typeof(Border));
  1157. factory.Bind<ContentControl, Brush>(Border.BorderBrushProperty, x => x.BorderBrush);
  1158. factory.Bind<ContentControl, Thickness>(Border.BorderThicknessProperty, x => x.BorderThickness);
  1159. factory.Bind<ContentControl, Brush>(Border.BackgroundProperty, x => x.Background);
  1160. factory.Bind<ContentControl, Thickness>(Border.PaddingProperty, x => x.Padding);
  1161. var content = new FrameworkElementFactory(typeof(ContentPresenter));
  1162. content.Bind<ContentControl, HorizontalAlignment>(ContentPresenter.HorizontalAlignmentProperty, x => x.HorizontalContentAlignment);
  1163. content.Bind<ContentControl, VerticalAlignment>(ContentPresenter.VerticalAlignmentProperty, x => x.VerticalContentAlignment);
  1164. factory.AppendChild(content);
  1165. template.VisualTree = factory;
  1166. Template = template;
  1167. }
  1168. }
  1169. private void RebuildSummaryRow()
  1170. {
  1171. if (_summaryRow is null) return;
  1172. _summaryRow.RowDefinitions.Clear();
  1173. _summaryRow.ColumnDefinitions.Clear();
  1174. _summaryRow.Children.Clear();
  1175. var row = _summaryRow.AddRow(GridUnitType.Auto);
  1176. row.MinHeight = _tree.RowHeight;
  1177. foreach(var (i, column) in _tree.Columns.WithIndex())
  1178. {
  1179. _summaryRow.AddColumn(column.ActualWidth);
  1180. var cell = new SummaryCellControl();
  1181. if(GetColumn(i) is DynamicColumnBase col)
  1182. {
  1183. cell.Style = GetSummaryCellStyle(col);
  1184. var summary = Summaries.FirstOrDefault(x => x.Column == col);
  1185. if(summary is not null)
  1186. {
  1187. cell.Content = summary.Data;
  1188. summary.Control = cell;
  1189. }
  1190. }
  1191. _summaryRow.AddChild(cell, 0, _summaryRow.ColumnDefinitions.Count - 1);
  1192. }
  1193. }
  1194. private void CalculateSummaries()
  1195. {
  1196. foreach(var column in ColumnList)
  1197. {
  1198. CalculateSummary(column);
  1199. }
  1200. }
  1201. private object? CalculateSummaryData(IDynamicGridSummary summary, DynamicColumnBase column)
  1202. {
  1203. var nodes = _tree.View is not null
  1204. ? _tree.View.Nodes.Select(x => x.Item as CoreTreeNode<TKey>).NotNull()
  1205. : Nodes.Nodes;
  1206. if(summary is DynamicGridCountSummary count)
  1207. {
  1208. return string.Format("{0:N0}", nodes.Count());
  1209. }
  1210. else if(summary is DynamicGridSumSummary sum)
  1211. {
  1212. if(column is DynamicGridColumn gridColumn)
  1213. {
  1214. var data = nodes.Select(x => MapRow(x.Row)).NotNull()
  1215. .Select(x => x[gridColumn.ColumnName]);
  1216. object? result;
  1217. if(sum.AggregateType == typeof(double))
  1218. {
  1219. result = data.Sum(x => x is double d ? d : 0);
  1220. }
  1221. else if(sum.AggregateType == typeof(int))
  1222. {
  1223. result = data.Sum(x => x is int i ? i : 0);
  1224. }
  1225. else if(sum.AggregateType == typeof(TimeSpan))
  1226. {
  1227. result = data.Aggregate(TimeSpan.Zero, (cur, x) => x is TimeSpan ts ? cur + ts : cur);
  1228. }
  1229. else
  1230. {
  1231. result = null;
  1232. }
  1233. if(result is not null)
  1234. {
  1235. return string.Format($"{{0:{sum.Format}}}", result);
  1236. }
  1237. }
  1238. }
  1239. else if(summary is DynamicGridCustomSummary custom)
  1240. {
  1241. var data = nodes.Select(x => MapRow(x.Row)).NotNull();
  1242. var result = custom.Aggregate(data);
  1243. if(result is not null)
  1244. {
  1245. return string.Format($"{{0:{custom.Format}}}", result);
  1246. }
  1247. }
  1248. else if(summary is DynamicGridTemplateSummary template)
  1249. {
  1250. return template.Template();
  1251. }
  1252. return null;
  1253. }
  1254. private void CalculateSummary(DynamicColumnBase column)
  1255. {
  1256. var (idx, summary) = Summaries.WithIndex().FirstOrDefault(x => x.Value.Column == column);
  1257. if(summary is null)
  1258. {
  1259. return;
  1260. }
  1261. var colIdx = ColumnList.IndexOf(summary.Column);
  1262. if(colIdx == -1)
  1263. {
  1264. return;
  1265. }
  1266. summary.Data = CalculateSummaryData(summary.SummaryDefinition, column);
  1267. if(summary.Control is not null)
  1268. {
  1269. summary.Control.Content = summary.Data;
  1270. }
  1271. }
  1272. #endregion
  1273. #region Refresh
  1274. public CoreTreeNodes<TKey> Nodes { get; set; }
  1275. private CoreTable? _innerTable;
  1276. private bool _invalidating = false;
  1277. public void BeforeRefresh()
  1278. {
  1279. if(_summaryRow is not null)
  1280. {
  1281. _summaryRow.Visibility = Visibility.Collapsed;
  1282. }
  1283. _tree.SelectionForeground = GetCellSelectionForegroundBrush();
  1284. _tree.SelectionBackground = GetCellSelectionBackgroundBrush();
  1285. }
  1286. public void RefreshData(CoreTable data)
  1287. {
  1288. var nodes = new CoreTreeNodes<TKey>(NullKey);
  1289. _innerTable = new CoreTable();
  1290. _innerTable.LoadColumns(data.Columns);
  1291. for (var i = 0; i < ActionColumns.Count; i++)
  1292. {
  1293. _innerTable.Columns.Add(
  1294. new CoreColumn
  1295. {
  1296. ColumnName = $"_ActionColumn{i}",
  1297. DataType = ActionColumns[i] is DynamicImageColumn
  1298. ? typeof(BitmapImage)
  1299. : typeof(String)
  1300. });
  1301. }
  1302. foreach (var row in data.Rows)
  1303. {
  1304. var newRow = _innerTable.NewRow();
  1305. ProcessRow(newRow, row);
  1306. _innerTable.Rows.Add(newRow);
  1307. nodes.Add(GetIDKey(row), GetParentKey(row), newRow);
  1308. }
  1309. nodes.ColumnChanged += Nodes_ColumnChanged;
  1310. Nodes = nodes;
  1311. _tree.ItemsSource = nodes.Nodes;
  1312. if(_summaryRow is not null && Summaries.Count > 0)
  1313. {
  1314. _summaryRow.Visibility = Visibility.Visible;
  1315. }
  1316. CalculateSummaries();
  1317. CalculateRowHeight();
  1318. ResizeColumns(_tree, _tree.ActualWidth - 1, _tree.ActualHeight);
  1319. UpdateRecordCount();
  1320. }
  1321. public void AddPage(IEnumerable<CoreRow> page)
  1322. {
  1323. if (_innerTable is null) return;
  1324. _invalidating = true;
  1325. foreach(var row in page)
  1326. {
  1327. var newRow = _innerTable.NewRow();
  1328. ProcessRow(newRow, row);
  1329. _innerTable.Rows.Add(newRow);
  1330. Nodes.Add(GetIDKey(row), GetParentKey(row), newRow);
  1331. }
  1332. CalculateSummaries();
  1333. CalculateRowHeight();
  1334. UpdateRecordCount();
  1335. _invalidating = false;
  1336. }
  1337. private void ProcessRow(CoreRow innerRow, CoreRow row)
  1338. {
  1339. innerRow.LoadValues(row.Values);
  1340. for (var i = 0; i < ActionColumns.Count; i++)
  1341. {
  1342. var ac = ActionColumns[i];
  1343. innerRow[$"_ActionColumn{i}"] = ac.Data(row);
  1344. }
  1345. }
  1346. private void CalculateRowHeight()
  1347. {
  1348. if(Parent.Data != null && Parent.Data.Rows.Count > 0)
  1349. {
  1350. var contentHeight = _tree.ActualHeight - (_tree.Padding.Top + _tree.Padding.Bottom) - 2; // Two extra pixels of space
  1351. var targetHeight = contentHeight / Parent.Data.Rows.Count;
  1352. _tree.RowHeight = Math.Max(Math.Min(targetHeight, MaxRowHeight), MinRowHeight);
  1353. }
  1354. }
  1355. private void UpdateRecordCount()
  1356. {
  1357. var count = _tree.View != null ? _tree.View.Nodes.Count : Parent.Data.Rows.Count;
  1358. Parent.UpdateRecordCount(count);
  1359. }
  1360. #endregion
  1361. #region Invalidation + Updating
  1362. public void InvalidateRow(CoreRow row)
  1363. {
  1364. if (_innerTable is null || row.Index < 0 || row.Index >= _innerTable.Rows.Count) return;
  1365. _invalidating = true;
  1366. var _innerRow = _innerTable.Rows[row.Index];
  1367. ProcessRow(_innerRow, row);
  1368. var coreTreeNode = Nodes.Find(_innerRow);
  1369. coreTreeNode?.InvalidateData();
  1370. CalculateSummaries();
  1371. _invalidating = false;
  1372. }
  1373. public void UpdateCell(CoreRow row, string column, object? value)
  1374. {
  1375. var node = GetNode(row);
  1376. if(node is not null)
  1377. {
  1378. node[column] = value;
  1379. node.InvalidateData();
  1380. }
  1381. }
  1382. public void UpdateCell(CoreRow row, DynamicColumnBase column)
  1383. {
  1384. var node = GetNode(row);
  1385. if(node is not null)
  1386. {
  1387. if(column is DynamicGridColumn gc)
  1388. {
  1389. node[gc.ColumnName] = row[gc.ColumnName];
  1390. }
  1391. else if(column is DynamicActionColumn ac)
  1392. {
  1393. var i = ActionColumns.IndexOf(ac);
  1394. node[$"_ActionColumn{i}"] = ac.Data(row);
  1395. }
  1396. }
  1397. }
  1398. public void UpdateRow(CoreRow row, CoreTreeNode<TKey> dataRow)
  1399. {
  1400. foreach(var (key, value) in row)
  1401. {
  1402. dataRow[key] = value;
  1403. }
  1404. for (var i = 0; i < ActionColumns.Count; i++)
  1405. dataRow[$"_ActionColumn{i}"] = ActionColumns[i].Data(row);
  1406. dataRow.InvalidateData();
  1407. }
  1408. public void UpdateRow(CoreRow row)
  1409. {
  1410. var dataRow = GetNode(row);
  1411. if(dataRow is not null)
  1412. {
  1413. UpdateRow(row, dataRow);
  1414. }
  1415. }
  1416. #endregion
  1417. public void ScrollIntoView(CoreRow row)
  1418. {
  1419. _tree.ScrollInView(new RowColumnIndex(row.Index + 1, 0));
  1420. }
  1421. #region Direct Edit
  1422. private void _tree_PreviewKeyUp(object sender, KeyEventArgs e)
  1423. {
  1424. if (e.Key == Key.OemPeriod)
  1425. {
  1426. if (e.OriginalSource is Syncfusion.Windows.Shared.TimeSpanEdit editor && editor.SelectionStart < 2)
  1427. {
  1428. editor.SelectionStart = 3;
  1429. }
  1430. }
  1431. else if (e.Key == Key.Tab)
  1432. {
  1433. if (Parent.IsDirectEditMode())
  1434. {
  1435. _tree.SelectionController.CurrentCellManager.EndEdit();
  1436. _tree.MoveFocus(new TraversalRequest(FocusNavigationDirection.Right));
  1437. _tree.SelectionController.CurrentCellManager.BeginEdit();
  1438. e.Handled = true;
  1439. }
  1440. }
  1441. else if(e.Key == Key.Escape)
  1442. {
  1443. if (Parent.IsDirectEditMode())
  1444. {
  1445. bChanged = false;
  1446. }
  1447. }
  1448. }
  1449. private bool bChanged;
  1450. private class DirectEditingObject
  1451. {
  1452. public T Object { get; set; }
  1453. public CoreRow Row { get; set; }
  1454. public CoreTreeNode<TKey>? Node { get; set; }
  1455. public DirectEditingObject(T obj, CoreRow row, CoreTreeNode<TKey>? node)
  1456. {
  1457. Object = obj;
  1458. Row = row;
  1459. Node = node;
  1460. }
  1461. }
  1462. private DirectEditingObject? _editingObject;
  1463. private DirectEditingObject EnsureEditingObject(CoreRow row)
  1464. {
  1465. _editingObject ??= new(Parent.LoadItem(row), row, GetNode(row));
  1466. return _editingObject;
  1467. }
  1468. private void DoEntityChanged(IDynamicColumnBase column, DynamicColumnEntityChangedEventArgs args)
  1469. {
  1470. if (_editingObject is null) return;
  1471. Parent.EntityChanged(_editingObject.Object, _editingObject.Row, args.ColumnName, args.Changes);
  1472. }
  1473. private void UpdateData(string column, Dictionary<CoreColumn, object?> updates)
  1474. {
  1475. if (_editingObject is null)
  1476. return;
  1477. var coreRow = _editingObject.Row;
  1478. try
  1479. {
  1480. Parent.UpdateData(_editingObject.Object, coreRow, column, updates);
  1481. }
  1482. catch(Exception e)
  1483. {
  1484. MessageWindow.ShowError($"Error saving {typeof(T)}", e);
  1485. }
  1486. }
  1487. private void UpdateData(CoreTreeNode<TKey> node, int columnIndex)
  1488. {
  1489. if (GetColumn(columnIndex) is DynamicGridColumn gridcol)
  1490. {
  1491. var datacol = Parent.Data.Columns.FirstOrDefault(x => x.ColumnName.Equals(gridcol.ColumnName));
  1492. if (datacol != null)
  1493. {
  1494. var value = node?[datacol.ColumnName];
  1495. if (value is null)
  1496. value = CoreUtils.GetDefault(datacol.DataType);
  1497. else
  1498. value = CoreUtils.ChangeType(value, datacol.DataType);
  1499. UpdateData(datacol.ColumnName, new Dictionary<CoreColumn, object?>() { { datacol, value } });
  1500. }
  1501. }
  1502. }
  1503. private Dictionary<string, CoreTable> _lookups = new();
  1504. private void _tree_CurrentCellBeginEdit(object? sender, TreeGridCurrentCellBeginEditEventArgs e)
  1505. {
  1506. var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
  1507. if (row is null)
  1508. return;
  1509. EnsureEditingObject(row);
  1510. if (_tree.Columns[e.RowColumnIndex.ColumnIndex] is TreeGridComboBoxColumn column && column.ItemsSource == null)
  1511. {
  1512. var gridColumn = GetColumn(e.RowColumnIndex.ColumnIndex);
  1513. if(gridColumn is DynamicGridColumn col)
  1514. {
  1515. var property = col.ColumnName;
  1516. var prop = CoreUtils.GetProperty(typeof(T), property);
  1517. var editor = prop.GetEditor();
  1518. if (editor is ILookupEditor lookupEditor)
  1519. {
  1520. if (!_lookups.ContainsKey(property))
  1521. _lookups[property] = lookupEditor.Values(typeof(T), property);
  1522. var combo = column;
  1523. combo.ItemsSource = _lookups[property].ToDictionary(_lookups[property].Columns[0].ColumnName, "Display");
  1524. combo.SelectedValuePath = "Key";
  1525. combo.DisplayMemberPath = "Value";
  1526. }
  1527. }
  1528. }
  1529. bChanged = false;
  1530. }
  1531. private void Nodes_ColumnChanged(CoreTreeNode<TKey> node, string column)
  1532. {
  1533. if (_invalidating) return;
  1534. var row = GetRow(node);
  1535. if (row is null)
  1536. return;
  1537. var data = Parent.Data;
  1538. var dataCol = Parent.Data.Columns.FirstOrDefault(x => x.ColumnName.Equals(column));
  1539. var col = ColumnList.OfType<DynamicGridColumn>()
  1540. .FirstOrDefault(x => x.ColumnName.Equals(column));
  1541. if (col is null || dataCol is null)
  1542. return;
  1543. CalculateSummary(col);
  1544. if (col is DynamicGridCheckBoxColumn<T>)
  1545. {
  1546. EnsureEditingObject(row);
  1547. if(_editingObject is not null)
  1548. {
  1549. var value = node[column];
  1550. _invalidating = true;
  1551. UpdateData(column, new Dictionary<CoreColumn, object?>() { { dataCol, value } });
  1552. _invalidating = false;
  1553. }
  1554. _editingObject = null;
  1555. }
  1556. if (_editingObject is not null)
  1557. bChanged = true;
  1558. }
  1559. private void _tree_CurrentCellDropDownSelectionChanged(object? sender, CurrentCellDropDownSelectionChangedEventArgs e)
  1560. {
  1561. var row = GetRowFromIndex(e.RowColumnIndex.RowIndex);
  1562. if (row is null)
  1563. return;
  1564. EnsureEditingObject(row);
  1565. if ((_editingObject is not null) && (e.SelectedItem is Tuple<object?, string> tuple))
  1566. {
  1567. var gridColumn = GetColumn(e.RowColumnIndex.ColumnIndex);
  1568. if (gridColumn is DynamicGridColumn col)
  1569. {
  1570. var corecol = col.ColumnName;
  1571. var updates = new Dictionary<CoreColumn, object?>();
  1572. var prefix = string.Join(".", corecol.Split(".").Reverse().Skip(1).Reverse());
  1573. var field = corecol.Split(".").Last();
  1574. var prop = CoreUtils.GetProperty(typeof(T), corecol);
  1575. if (prop.GetEditor() is ILookupEditor editor)
  1576. {
  1577. var data = editor.Values(typeof(T), corecol);
  1578. var lookuprow = data.Rows.FirstOrDefault(r => Equals(r[field], tuple.Item1))
  1579. ?? data.NewRow(true);
  1580. foreach (CoreColumn lookupcol in data.Columns)
  1581. {
  1582. var columnname = String.IsNullOrWhiteSpace(prefix)
  1583. ? lookupcol.ColumnName
  1584. : String.Join(".", prefix, lookupcol.ColumnName);
  1585. var updatecol = Parent.Data.Columns.FirstOrDefault(x => String.Equals(x.ColumnName, columnname));
  1586. if (updatecol != null)
  1587. updates[updatecol] = lookuprow[lookupcol.ColumnName];
  1588. }
  1589. UpdateData(corecol, updates);
  1590. bChanged = true;
  1591. }
  1592. }
  1593. }
  1594. }
  1595. private void CancelEdit()
  1596. {
  1597. var obj = _editingObject;
  1598. bChanged = false;
  1599. _editingObject = null;
  1600. _tree.SelectionController.CurrentCellManager.EndEdit(false);
  1601. if(obj is not null)
  1602. {
  1603. UpdateRow(obj.Row, obj.Node);
  1604. }
  1605. }
  1606. private void _tree_CurrentCellEndEdit(object? sender, CurrentCellEndEditEventArgs e)
  1607. {
  1608. if (_editingObject is not null && bChanged)
  1609. {
  1610. UpdateData(_editingObject.Node, e.RowColumnIndex.ColumnIndex);
  1611. }
  1612. if (bChanged)
  1613. Parent.DoChanged();
  1614. bChanged = false;
  1615. _editingObject = null;
  1616. }
  1617. #endregion
  1618. #region Drag + Drop
  1619. private void _tree_DragOver(object sender, DragEventArgs e)
  1620. {
  1621. Parent.DragOver(sender, e);
  1622. }
  1623. private void _tree_Drop(object sender, DragEventArgs e)
  1624. {
  1625. Parent.Drop(sender, e);
  1626. }
  1627. private void RowDragDropController_DragStart(object? sender, TreeGridRowDragStartEventArgs e)
  1628. {
  1629. var rows = e.DraggingNodes.Select(node => MapRow((node.Item as CoreTreeNode<TKey>)?.Row)).NotNull().ToArray();
  1630. Parent.DragStart(sender, rows);
  1631. }
  1632. #endregion
  1633. }