DataGridCellsPresenter.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358
  1. // (c) Copyright Microsoft Corporation.
  2. // This source is subject to the Microsoft Public License (Ms-PL).
  3. // Please see http://go.microsoft.com/fwlink/?LinkID=131993 for details.
  4. // All other rights reserved.
  5. using Avalonia.LogicalTree;
  6. using Avalonia.Media;
  7. using Avalonia.Utilities;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Collections.Specialized;
  11. using System.Diagnostics;
  12. namespace Avalonia.Controls.Primitives
  13. {
  14. /// <summary>
  15. /// Used within the template of a <see cref="T:Avalonia.Controls.DataGrid" />
  16. /// to specify the location in the control's visual tree where the cells are to be added.
  17. /// </summary>
  18. public sealed class DataGridCellsPresenter : Panel, IChildIndexProvider
  19. {
  20. private double _fillerLeftEdge;
  21. private EventHandler<ChildIndexChangedEventArgs> _childIndexChanged;
  22. // The desired height needs to be cached due to column virtualization; otherwise, the cells
  23. // would grow and shrink as the DataGrid scrolls horizontally
  24. private double DesiredHeight
  25. {
  26. get;
  27. set;
  28. }
  29. private DataGrid OwningGrid
  30. {
  31. get
  32. {
  33. return OwningRow?.OwningGrid;
  34. }
  35. }
  36. internal DataGridRow OwningRow
  37. {
  38. get;
  39. set;
  40. }
  41. event EventHandler<ChildIndexChangedEventArgs> IChildIndexProvider.ChildIndexChanged
  42. {
  43. add => _childIndexChanged += value;
  44. remove => _childIndexChanged -= value;
  45. }
  46. int IChildIndexProvider.GetChildIndex(ILogical child)
  47. {
  48. return child is DataGridCell cell
  49. ? cell.OwningColumn?.DisplayIndex ?? -1
  50. : throw new InvalidOperationException("Invalid cell type");
  51. }
  52. bool IChildIndexProvider.TryGetTotalCount(out int count)
  53. {
  54. count = Children.Count - 1; // Adjust for filler column
  55. return true;
  56. }
  57. /// <summary>
  58. /// Arranges the content of the <see cref="T:Avalonia.Controls.Primitives.DataGridCellsPresenter" />.
  59. /// </summary>
  60. /// <returns>
  61. /// The actual size used by the <see cref="T:Avalonia.Controls.Primitives.DataGridCellsPresenter" />.
  62. /// </returns>
  63. /// <param name="finalSize">
  64. /// The final area within the parent that this element should use to arrange itself and its children.
  65. /// </param>
  66. protected override Size ArrangeOverride(Size finalSize)
  67. {
  68. if (OwningGrid == null)
  69. {
  70. return base.ArrangeOverride(finalSize);
  71. }
  72. if (OwningGrid.AutoSizingColumns)
  73. {
  74. // When we initially load an auto-column, we have to wait for all the rows to be measured
  75. // before we know its final desired size. We need to trigger a new round of measures now
  76. // that the final sizes have been calculated.
  77. OwningGrid.AutoSizingColumns = false;
  78. return base.ArrangeOverride(finalSize);
  79. }
  80. double frozenLeftEdge = 0;
  81. double scrollingLeftEdge = -OwningGrid.HorizontalOffset;
  82. double cellLeftEdge;
  83. foreach (DataGridColumn column in OwningGrid.ColumnsInternal.GetVisibleColumns())
  84. {
  85. DataGridCell cell = OwningRow.Cells[column.Index];
  86. Debug.Assert(cell.OwningColumn == column);
  87. Debug.Assert(column.IsVisible);
  88. if (column.IsFrozen)
  89. {
  90. cellLeftEdge = frozenLeftEdge;
  91. // This can happen before or after clipping because frozen cells aren't clipped
  92. frozenLeftEdge += column.ActualWidth;
  93. }
  94. else
  95. {
  96. cellLeftEdge = scrollingLeftEdge;
  97. }
  98. if (cell.IsVisible)
  99. {
  100. cell.Arrange(new Rect(cellLeftEdge, 0, column.LayoutRoundedWidth, finalSize.Height));
  101. EnsureCellClip(cell, column.ActualWidth, finalSize.Height, frozenLeftEdge, scrollingLeftEdge);
  102. }
  103. scrollingLeftEdge += column.ActualWidth;
  104. column.IsInitialDesiredWidthDetermined = true;
  105. }
  106. _fillerLeftEdge = scrollingLeftEdge;
  107. OwningRow.FillerCell.Arrange(new Rect(_fillerLeftEdge, 0, OwningGrid.ColumnsInternal.FillerColumn.FillerWidth, finalSize.Height));
  108. return finalSize;
  109. }
  110. private static void EnsureCellClip(DataGridCell cell, double width, double height, double frozenLeftEdge, double cellLeftEdge)
  111. {
  112. // Clip the cell only if it's scrolled under frozen columns. Unfortunately, we need to clip in this case
  113. // because cells could be transparent
  114. if (!cell.OwningColumn.IsFrozen && frozenLeftEdge > cellLeftEdge)
  115. {
  116. RectangleGeometry rg = new RectangleGeometry();
  117. double xClip = Math.Round(Math.Min(width, frozenLeftEdge - cellLeftEdge));
  118. rg.Rect = new Rect(xClip, 0, Math.Max(0, width - xClip), height);
  119. cell.Clip = rg;
  120. }
  121. else
  122. {
  123. cell.Clip = null;
  124. }
  125. }
  126. protected override void ChildrenChanged(object sender, NotifyCollectionChangedEventArgs e)
  127. {
  128. base.ChildrenChanged(sender, e);
  129. InvalidateChildIndex();
  130. }
  131. private static void EnsureCellDisplay(DataGridCell cell, bool displayColumn)
  132. {
  133. if (cell.IsCurrent)
  134. {
  135. if (displayColumn)
  136. {
  137. cell.IsVisible = true;
  138. cell.Clip = null;
  139. }
  140. else
  141. {
  142. // Clip
  143. RectangleGeometry rg = new RectangleGeometry();
  144. rg.Rect = default;
  145. cell.Clip = rg;
  146. }
  147. }
  148. else
  149. {
  150. cell.IsVisible = displayColumn;
  151. }
  152. }
  153. internal void EnsureFillerVisibility()
  154. {
  155. DataGridFillerColumn fillerColumn = OwningGrid.ColumnsInternal.FillerColumn;
  156. bool newVisibility = fillerColumn.IsActive;
  157. if (OwningRow.FillerCell.IsVisible != newVisibility)
  158. {
  159. OwningRow.FillerCell.IsVisible = newVisibility;
  160. if (newVisibility)
  161. {
  162. OwningRow.FillerCell.Arrange(new Rect(_fillerLeftEdge, 0, fillerColumn.FillerWidth, Bounds.Height));
  163. }
  164. }
  165. // This must be done after the Filler visibility is determined. This also must be done
  166. // regardless of whether or not the filler visibility actually changed values because
  167. // we could scroll in a cell that didn't have EnsureGridLine called yet
  168. DataGridColumn lastVisibleColumn = OwningGrid.ColumnsInternal.LastVisibleColumn;
  169. if (lastVisibleColumn != null)
  170. {
  171. DataGridCell cell = OwningRow.Cells[lastVisibleColumn.Index];
  172. cell.EnsureGridLine(lastVisibleColumn);
  173. }
  174. }
  175. /// <summary>
  176. /// Measures the children of a <see cref="T:Avalonia.Controls.Primitives.DataGridCellsPresenter" /> to
  177. /// prepare for arranging them during the <see cref="M:System.Windows.FrameworkElement.ArrangeOverride(System.Windows.Size)" /> pass.
  178. /// </summary>
  179. /// <param name="availableSize">
  180. /// The available size that this element can give to child elements. Indicates an upper limit that child elements should not exceed.
  181. /// </param>
  182. /// <returns>
  183. /// The size that the <see cref="T:Avalonia.Controls.Primitives.DataGridCellsPresenter" /> determines it needs during layout, based on its calculations of child object allocated sizes.
  184. /// </returns>
  185. protected override Size MeasureOverride(Size availableSize)
  186. {
  187. if (OwningGrid == null)
  188. {
  189. return base.MeasureOverride(availableSize);
  190. }
  191. bool autoSizeHeight;
  192. double measureHeight;
  193. if (double.IsNaN(OwningGrid.RowHeight))
  194. {
  195. // No explicit height values were set so we can autosize
  196. autoSizeHeight = true;
  197. // We need to invalidate desired height in order to grow or shrink as needed
  198. InvalidateDesiredHeight();
  199. measureHeight = double.PositiveInfinity;
  200. }
  201. else
  202. {
  203. DesiredHeight = OwningGrid.RowHeight;
  204. measureHeight = DesiredHeight;
  205. autoSizeHeight = false;
  206. }
  207. double frozenLeftEdge = 0;
  208. double totalDisplayWidth = 0;
  209. double scrollingLeftEdge = -OwningGrid.HorizontalOffset;
  210. OwningGrid.ColumnsInternal.EnsureVisibleEdgedColumnsWidth();
  211. DataGridColumn lastVisibleColumn = OwningGrid.ColumnsInternal.LastVisibleColumn;
  212. foreach (DataGridColumn column in OwningGrid.ColumnsInternal.GetVisibleColumns())
  213. {
  214. DataGridCell cell = OwningRow.Cells[column.Index];
  215. // Measure the entire first row to make the horizontal scrollbar more accurate
  216. bool shouldDisplayCell = ShouldDisplayCell(column, frozenLeftEdge, scrollingLeftEdge) || OwningRow.Index == 0;
  217. EnsureCellDisplay(cell, shouldDisplayCell);
  218. if (shouldDisplayCell)
  219. {
  220. DataGridLength columnWidth = column.Width;
  221. bool autoGrowWidth = columnWidth.IsSizeToCells || columnWidth.IsAuto;
  222. if (column != lastVisibleColumn)
  223. {
  224. cell.EnsureGridLine(lastVisibleColumn);
  225. }
  226. // If we're not using star sizing or the current column can't be resized,
  227. // then just set the display width according to the column's desired width
  228. if (!OwningGrid.UsesStarSizing || (!column.ActualCanUserResize && !column.Width.IsStar))
  229. {
  230. // In the edge-case where we're given infinite width and we have star columns, the
  231. // star columns grow to their predefined limit of 10,000 (or their MaxWidth)
  232. double newDisplayWidth = column.Width.IsStar ?
  233. Math.Min(column.ActualMaxWidth, DataGrid.DATAGRID_maximumStarColumnWidth) :
  234. Math.Max(column.ActualMinWidth, Math.Min(column.ActualMaxWidth, column.Width.DesiredValue));
  235. column.SetWidthDisplayValue(newDisplayWidth);
  236. }
  237. // If we're auto-growing the column based on the cell content, we want to measure it at its maximum value
  238. if (autoGrowWidth)
  239. {
  240. cell.Measure(new Size(column.ActualMaxWidth, measureHeight));
  241. OwningGrid.AutoSizeColumn(column, cell.DesiredSize.Width);
  242. column.ComputeLayoutRoundedWidth(totalDisplayWidth);
  243. }
  244. else if (!OwningGrid.UsesStarSizing)
  245. {
  246. column.ComputeLayoutRoundedWidth(scrollingLeftEdge);
  247. cell.Measure(new Size(column.LayoutRoundedWidth, measureHeight));
  248. }
  249. // We need to track the largest height in order to auto-size
  250. if (autoSizeHeight)
  251. {
  252. DesiredHeight = Math.Max(DesiredHeight, cell.DesiredSize.Height);
  253. }
  254. }
  255. if (column.IsFrozen)
  256. {
  257. frozenLeftEdge += column.ActualWidth;
  258. }
  259. scrollingLeftEdge += column.ActualWidth;
  260. totalDisplayWidth += column.ActualWidth;
  261. }
  262. // If we're using star sizing (and we're not waiting for an auto-column to finish growing)
  263. // then we will resize all the columns to fit the available space.
  264. if (OwningGrid.UsesStarSizing && !OwningGrid.AutoSizingColumns)
  265. {
  266. double adjustment = OwningGrid.CellsWidth - totalDisplayWidth;
  267. totalDisplayWidth += adjustment - OwningGrid.AdjustColumnWidths(0, adjustment, false);
  268. // Since we didn't know the final widths of the columns until we resized,
  269. // we waited until now to measure each cell
  270. double leftEdge = 0;
  271. if (autoSizeHeight)
  272. DesiredHeight = 0;
  273. foreach (DataGridColumn column in OwningGrid.ColumnsInternal.GetVisibleColumns())
  274. {
  275. DataGridCell cell = OwningRow.Cells[column.Index];
  276. column.ComputeLayoutRoundedWidth(leftEdge);
  277. cell.Measure(new Size(column.LayoutRoundedWidth, measureHeight));
  278. if (autoSizeHeight)
  279. {
  280. DesiredHeight = Math.Max(DesiredHeight, cell.DesiredSize.Height);
  281. }
  282. leftEdge += column.ActualWidth;
  283. }
  284. }
  285. // Measure FillerCell, we're doing it unconditionally here because we don't know if we'll need the filler
  286. // column and we don't want to cause another Measure if we do
  287. OwningRow.FillerCell.Measure(new Size(double.PositiveInfinity, DesiredHeight));
  288. OwningGrid.ColumnsInternal.EnsureVisibleEdgedColumnsWidth();
  289. return new Size(OwningGrid.ColumnsInternal.VisibleEdgedColumnsWidth, DesiredHeight);
  290. }
  291. internal void Recycle()
  292. {
  293. // Clear out the cached desired height so it is not reused for other rows
  294. DesiredHeight = 0;
  295. }
  296. internal void InvalidateDesiredHeight()
  297. {
  298. DesiredHeight = 0;
  299. }
  300. internal void InvalidateChildIndex()
  301. {
  302. _childIndexChanged?.Invoke(this, ChildIndexChangedEventArgs.ChildIndexesReset);
  303. }
  304. private bool ShouldDisplayCell(DataGridColumn column, double frozenLeftEdge, double scrollingLeftEdge)
  305. {
  306. if (!column.IsVisible)
  307. {
  308. return false;
  309. }
  310. scrollingLeftEdge += OwningGrid.HorizontalAdjustment;
  311. double leftEdge = column.IsFrozen ? frozenLeftEdge : scrollingLeftEdge;
  312. double rightEdge = leftEdge + column.ActualWidth;
  313. return
  314. MathUtilities.GreaterThan(rightEdge, 0) &&
  315. MathUtilities.LessThanOrClose(leftEdge, OwningGrid.CellsWidth) &&
  316. MathUtilities.GreaterThan(rightEdge, frozenLeftEdge); // scrolling column covered up by frozen column(s)
  317. }
  318. }
  319. }