AvaloniaDataGrid.axaml.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. using Avalonia;
  2. using Avalonia.Collections;
  3. using Avalonia.Controls;
  4. using Avalonia.Controls.Primitives;
  5. using Avalonia.Data;
  6. using Avalonia.Data.Converters;
  7. using Avalonia.Input;
  8. using Avalonia.Markup.Xaml;
  9. using Avalonia.Media;
  10. using Avalonia.Styling;
  11. using Avalonia.VisualTree;
  12. using CommunityToolkit.Mvvm.Input;
  13. using InABox.Core;
  14. using System.Collections;
  15. using System.ComponentModel;
  16. namespace InABox.Avalonia.Components;
  17. public class AvaloniaDataGridSelectionChangedEventArgs(object?[] selection)
  18. {
  19. public object?[] Selection { get; set; } = selection;
  20. }
  21. public class AvaloniaDataGridRefreshRequestedEventArgs()
  22. {
  23. }
  24. public enum AvaloniaDataGridSelectionMode
  25. {
  26. None,
  27. Single,
  28. Multiple
  29. }
  30. public partial class AvaloniaDataGrid : UserControl, INotifyPropertyChanged
  31. {
  32. public static StyledProperty<bool> CanSearchProperty =
  33. AvaloniaProperty.Register<AvaloniaDataGrid, bool>(nameof(CanSearch), true);
  34. public static StyledProperty<IEnumerable> ItemsSourceProperty =
  35. AvaloniaProperty.Register<AvaloniaDataGrid, IEnumerable>(nameof(ItemsSource));
  36. public static StyledProperty<DateTime> LastUpdatedProperty =
  37. AvaloniaProperty.Register<AvaloniaDataGrid, DateTime>(nameof(LastUpdated));
  38. public static StyledProperty<bool> ShowRecordCountProperty =
  39. AvaloniaProperty.Register<AvaloniaDataGrid, bool>(nameof(ShowRecordCount));
  40. public static StyledProperty<bool> RefreshVisibleProperty =
  41. AvaloniaProperty.Register<AvaloniaDataGrid, bool>(nameof(RefreshVisible));
  42. public static StyledProperty<AvaloniaDataGridSelectionMode> SelectionModeProperty =
  43. AvaloniaProperty.Register<AvaloniaDataGrid, AvaloniaDataGridSelectionMode>(nameof(SelectionMode), AvaloniaDataGridSelectionMode.Single);
  44. public static StyledProperty<double> RowHeightProperty =
  45. AvaloniaProperty.Register<AvaloniaDataGrid, double>(nameof(RowHeight), 30);
  46. public static StyledProperty<AvaloniaDataGridColumns?> ColumnsProperty =
  47. AvaloniaProperty.Register<AvaloniaDataGrid, AvaloniaDataGridColumns?>(nameof(Columns), null);
  48. public string SearchText { get; set; } = "";
  49. public bool CanSearch
  50. {
  51. get => GetValue(CanSearchProperty);
  52. set => SetValue(CanSearchProperty, value);
  53. }
  54. public IEnumerable ItemsSource
  55. {
  56. get => GetValue(ItemsSourceProperty);
  57. set => SetValue(ItemsSourceProperty, value);
  58. }
  59. public bool ShowRecordCount
  60. {
  61. get => GetValue(ShowRecordCountProperty);
  62. set => SetValue(ShowRecordCountProperty, value);
  63. }
  64. public bool RefreshVisible
  65. {
  66. get => GetValue(RefreshVisibleProperty);
  67. set => SetValue(RefreshVisibleProperty, value);
  68. }
  69. public AvaloniaDataGridSelectionMode SelectionMode
  70. {
  71. get => GetValue(SelectionModeProperty);
  72. set => SetValue(SelectionModeProperty, value);
  73. }
  74. public double RowHeight
  75. {
  76. get => GetValue(RowHeightProperty);
  77. set => SetValue(RowHeightProperty, value);
  78. }
  79. public int ItemCount { get; set; }
  80. public DateTime LastUpdated
  81. {
  82. get => GetValue(LastUpdatedProperty);
  83. set => SetValue(LastUpdatedProperty, value);
  84. }
  85. public AvaloniaDataGridColumns Columns { get; private set; }
  86. public IEnumerable<object?> SelectedItems => Grid.SelectedItems.Cast<object?>();
  87. public event EventHandler<AvaloniaDataGridSelectionChangedEventArgs>? SelectionChanged;
  88. public event EventHandler<AvaloniaDataGridRefreshRequestedEventArgs>? RefreshRequested;
  89. public event Predicate<object?>? FilterRow;
  90. public event EventHandler<DataGridRowEventArgs>? LoadingRow;
  91. #region Static Constructor and Property Changed Handlers
  92. static AvaloniaDataGrid()
  93. {
  94. ItemsSourceProperty.Changed.AddClassHandler<AvaloniaDataGrid>(ItemsSource_Changed);
  95. LastUpdatedProperty.Changed.AddClassHandler<AvaloniaDataGrid>(LastUpdated_Changed);
  96. ShowRecordCountProperty.Changed.AddClassHandler<AvaloniaDataGrid>(ShowRecordCount_Changed);
  97. ColumnsProperty.Changed.AddClassHandler<AvaloniaDataGrid>(ColumnsProperty_Changed);
  98. }
  99. private static void ColumnsProperty_Changed(AvaloniaDataGrid grid, AvaloniaPropertyChangedEventArgs args)
  100. {
  101. var columns = grid.GetValue(ColumnsProperty);
  102. if(columns is not null)
  103. {
  104. grid.Columns.BeginUpdate().AddRange(columns).EndUpdate();
  105. }
  106. }
  107. private static void ShowRecordCount_Changed(AvaloniaDataGrid grid, AvaloniaPropertyChangedEventArgs args)
  108. {
  109. grid.UpdateSummaryRow();
  110. }
  111. private static void LastUpdated_Changed(AvaloniaDataGrid grid, AvaloniaPropertyChangedEventArgs args)
  112. {
  113. grid.UpdateSummaryRow();
  114. }
  115. private static void ItemsSource_Changed(AvaloniaDataGrid grid, AvaloniaPropertyChangedEventArgs args)
  116. {
  117. grid.Grid.ItemsSource = grid.ItemsSource;
  118. if (grid.Grid.CollectionView is not null)
  119. {
  120. grid.Grid.CollectionView.CollectionChanged -= grid.CollectionView_CollectionChanged;
  121. grid.Grid.CollectionView.CollectionChanged += grid.CollectionView_CollectionChanged;
  122. }
  123. grid.ItemsChanged();
  124. grid.UpdateSummaryRow();
  125. }
  126. #endregion
  127. public AvaloniaDataGrid()
  128. {
  129. InitializeComponent();
  130. Columns = new AvaloniaDataGridColumns();
  131. Columns.Changed += Columns_Changed;
  132. Grid.Bind(DataGrid.SelectionModeProperty, new Binding(nameof(SelectionMode))
  133. {
  134. Source = this,
  135. Converter = new FuncValueConverter<AvaloniaDataGridSelectionMode, DataGridSelectionMode>(x => x switch
  136. {
  137. AvaloniaDataGridSelectionMode.Multiple => DataGridSelectionMode.Extended,
  138. AvaloniaDataGridSelectionMode.Single or AvaloniaDataGridSelectionMode.None or _ => DataGridSelectionMode.Single,
  139. })
  140. });
  141. }
  142. private void DataGrid_LoadingRow(object? sender, DataGridRowEventArgs e)
  143. {
  144. LoadingRow?.Invoke(this, e);
  145. }
  146. private void CollectionView_CollectionChanged(object? sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
  147. {
  148. ItemsChanged();
  149. }
  150. private void ItemsChanged()
  151. {
  152. ItemCount = (Grid.CollectionView as DataGridCollectionView)?.ItemCount ?? 0;
  153. }
  154. private void Columns_Changed(AvaloniaDataGridColumns columns)
  155. {
  156. Grid.Columns.Clear();
  157. foreach(var column in columns)
  158. {
  159. Grid.Columns.Add(column.CreateColumn());
  160. }
  161. // Summaries
  162. var searchableColumns = Columns.Any(x => x.Searchable);
  163. SearchBar.IsVisible = searchableColumns && CanSearch;
  164. }
  165. private void UpdateSummaryRow()
  166. {
  167. _lastUpdated.IsVisible = LastUpdated != DateTime.MinValue;
  168. _recordCount.Content = $" {ItemCount} records";
  169. _recordCount.IsVisible = ShowRecordCount && ItemsSource is IEnumerable;
  170. _recordCountBox.IsVisible = _recordCount.IsVisible || _lastUpdated.IsVisible;
  171. }
  172. public void ClearSelection()
  173. {
  174. Grid.SelectedItem = null;
  175. Grid.SelectedItems.Clear();
  176. }
  177. private bool DoSearch(object? item)
  178. {
  179. if (SearchText.IsNullOrWhiteSpace()) return true;
  180. if (item is null) return false;
  181. foreach(var column in Columns)
  182. {
  183. if(column.Filter(item, SearchText)) return true;
  184. }
  185. return false;
  186. }
  187. private bool DoFilter(object? item)
  188. {
  189. return DoSearch(item) && (FilterRow is null || FilterRow(item));
  190. }
  191. public void InvalidateGrid()
  192. {
  193. if (Grid.CollectionView is null) return;
  194. Grid.CollectionView.Filter = DoFilter;
  195. Grid.CollectionView.Refresh();
  196. UpdateSummaryRow();
  197. }
  198. [RelayCommand]
  199. private void Search()
  200. {
  201. if (Grid.CollectionView is null) return;
  202. Grid.CollectionView.Filter = DoFilter;
  203. Grid.CollectionView.Refresh();
  204. UpdateSummaryRow();
  205. }
  206. [RelayCommand]
  207. private void Refresh()
  208. {
  209. if (Grid.CollectionView is null) return;
  210. RefreshRequested?.Invoke(this, new());
  211. Grid.CollectionView.Refresh();
  212. }
  213. private void DataGrid_SelectionChanged(object sender, SelectionChangedEventArgs e)
  214. {
  215. if(SelectionMode == AvaloniaDataGridSelectionMode.None && Grid.SelectedItems.Count > 0)
  216. {
  217. e.Handled = true;
  218. Grid.SelectedItem = null;
  219. return;
  220. }
  221. if (SelectionMode != AvaloniaDataGridSelectionMode.Multiple) return;
  222. SelectionChanged?.Invoke(this, new AvaloniaDataGridSelectionChangedEventArgs(SelectedItems.ToArray()));
  223. }
  224. private void DataGrid_Tapped(object sender, TappedEventArgs e)
  225. {
  226. if (SelectionMode == AvaloniaDataGridSelectionMode.Multiple) return;
  227. var position = e.GetPosition(Grid);
  228. var parent = (e.Source as Visual)?.GetVisualAncestors().Where(x => x is DataGridCell || x is DataGridColumnHeader).FirstOrDefault();
  229. if (parent is null) return;
  230. if(parent is DataGridCell cell)
  231. {
  232. var cellCollection = cell.GetVisualParent<DataGridCellsPresenter>();
  233. if (cellCollection is null) return;
  234. var colIdx = cellCollection.Children.IndexOf(cell);
  235. var row = cellCollection.GetVisualAncestors().OfType<DataGridRow>().FirstOrDefault();
  236. if (row is null) return;
  237. var rowCollection = row.GetVisualParent<DataGridRowsPresenter>();
  238. if (rowCollection is null) return;
  239. var rowIdx = row.Index;
  240. var item = (Grid.CollectionView as DataGridCollectionView)?.GetItemAt(rowIdx);
  241. var column = Columns[colIdx];
  242. if(column.Tapped is not null)
  243. {
  244. column.Tapped?.Invoke(column, item);
  245. }
  246. else
  247. {
  248. SelectionChanged?.Invoke(this, new AvaloniaDataGridSelectionChangedEventArgs(new object?[] { item }));
  249. }
  250. }
  251. else if(parent is DataGridColumnHeader header)
  252. {
  253. var headerCollection = header.GetVisualParent<DataGridColumnHeadersPresenter>();
  254. if (headerCollection is null) return;
  255. var colIdx = headerCollection.Children.IndexOf(header);
  256. var column = Columns[colIdx];
  257. if(column.Tapped is not null)
  258. {
  259. column.Tapped?.Invoke(column, null);
  260. }
  261. else
  262. {
  263. SelectionChanged?.Invoke(this, new AvaloniaDataGridSelectionChangedEventArgs(Array.Empty<object?>()));
  264. }
  265. }
  266. }
  267. }