VirtualizingPanelBase.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Collections.ObjectModel;
  4. using System.Collections.Specialized;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. using System.Windows.Controls.Primitives;
  10. using System.Windows.Controls;
  11. using System.Windows.Media;
  12. using System.Windows;
  13. namespace GeekDesk.CustomComponent.VirtualizingWrapPanel
  14. {
  15. public abstract class VirtualizingPanelBase : VirtualizingPanel, IScrollInfo
  16. {
  17. public static readonly DependencyProperty ScrollLineDeltaProperty = DependencyProperty.Register(nameof(ScrollLineDelta), typeof(double), typeof(VirtualizingPanelBase), new FrameworkPropertyMetadata(16.0));
  18. public static readonly DependencyProperty MouseWheelDeltaProperty = DependencyProperty.Register(nameof(MouseWheelDelta), typeof(double), typeof(VirtualizingPanelBase), new FrameworkPropertyMetadata(48.0));
  19. public static readonly DependencyProperty ScrollLineDeltaItemProperty = DependencyProperty.Register(nameof(ScrollLineDeltaItem), typeof(int), typeof(VirtualizingPanelBase), new FrameworkPropertyMetadata(1));
  20. public static readonly DependencyProperty MouseWheelDeltaItemProperty = DependencyProperty.Register(nameof(MouseWheelDeltaItem), typeof(int), typeof(VirtualizingPanelBase), new FrameworkPropertyMetadata(3));
  21. private ScrollViewer scrollOwner;
  22. public ScrollViewer GetScrollOwner()
  23. {
  24. return scrollOwner;
  25. }
  26. public void SetScrollOwner(ScrollViewer value)
  27. {
  28. scrollOwner = value;
  29. }
  30. public bool CanVerticallyScroll { get; set; }
  31. public bool CanHorizontallyScroll { get; set; }
  32. protected override bool CanHierarchicallyScrollAndVirtualizeCore => true;
  33. /// <summary>
  34. /// Scroll line delta for pixel based scrolling. The default value is 16 dp.
  35. /// </summary>
  36. public double ScrollLineDelta { get => (double)GetValue(ScrollLineDeltaProperty); set => SetValue(ScrollLineDeltaProperty, value); }
  37. /// <summary>
  38. /// Mouse wheel delta for pixel based scrolling. The default value is 48 dp.
  39. /// </summary>
  40. public double MouseWheelDelta { get => (double)GetValue(MouseWheelDeltaProperty); set => SetValue(MouseWheelDeltaProperty, value); }
  41. /// <summary>
  42. /// Scroll line delta for item based scrolling. The default value is 1 item.
  43. /// </summary>
  44. public double ScrollLineDeltaItem { get => (int)GetValue(ScrollLineDeltaItemProperty); set => SetValue(ScrollLineDeltaItemProperty, value); }
  45. /// <summary>
  46. /// Mouse wheel delta for item based scrolling. The default value is 3 items.
  47. /// </summary>
  48. public int MouseWheelDeltaItem { get => (int)GetValue(MouseWheelDeltaItemProperty); set => SetValue(MouseWheelDeltaItemProperty, value); }
  49. protected ScrollUnit ScrollUnit => GetScrollUnit(ItemsControl);
  50. /// <summary>
  51. /// The direction in which the panel scrolls when user turns the mouse wheel.
  52. /// </summary>
  53. protected ScrollDirection MouseWheelScrollDirection { get; set; } = ScrollDirection.Vertical;
  54. protected bool IsVirtualizing => GetIsVirtualizing(ItemsControl);
  55. protected VirtualizationMode VirtualizationMode => GetVirtualizationMode(ItemsControl);
  56. /// <summary>
  57. /// Returns true if the panel is in VirtualizationMode.Recycling, otherwise false.
  58. /// </summary>
  59. protected bool IsRecycling => VirtualizationMode == VirtualizationMode.Recycling;
  60. /// <summary>
  61. /// The cache length before and after the viewport.
  62. /// </summary>
  63. protected VirtualizationCacheLength CacheLength { get; private set; }
  64. /// <summary>
  65. /// The Unit of the cache length. Can be Pixel, Item or Page.
  66. /// When the ItemsOwner is a group item it can only be pixel or item.
  67. /// </summary>
  68. protected VirtualizationCacheLengthUnit CacheLengthUnit { get; private set; }
  69. /// <summary>
  70. /// The ItemsControl (e.g. ListView).
  71. /// </summary>
  72. protected ItemsControl ItemsControl => ItemsControl.GetItemsOwner(this);
  73. /// <summary>
  74. /// The ItemsControl (e.g. ListView) or if the ItemsControl is grouping a GroupItem.
  75. /// </summary>
  76. protected DependencyObject ItemsOwner
  77. {
  78. get
  79. {
  80. if (ItemsOwner1 is null)
  81. {
  82. /* Use reflection to access internal method because the public
  83. * GetItemsOwner method does always return the itmes control instead
  84. * of the real items owner for example the group item when grouping */
  85. MethodInfo getItemsOwnerInternalMethod = typeof(ItemsControl).GetMethod(
  86. "GetItemsOwnerInternal",
  87. BindingFlags.Static | BindingFlags.NonPublic,
  88. null,
  89. new Type[] { typeof(DependencyObject) },
  90. null
  91. );
  92. ItemsOwner1 = (DependencyObject)getItemsOwnerInternalMethod.Invoke(null, new object[] { this });
  93. }
  94. return ItemsOwner1;
  95. }
  96. }
  97. private DependencyObject _itemsOwner;
  98. protected ReadOnlyCollection<object> Items => ((ItemContainerGenerator)ItemContainerGenerator).Items;
  99. protected new IRecyclingItemContainerGenerator ItemContainerGenerator
  100. {
  101. get
  102. {
  103. if (_itemContainerGenerator is null)
  104. {
  105. /* Because of a bug in the framework the ItemContainerGenerator
  106. * is null until InternalChildren accessed at least one time. */
  107. var children = InternalChildren;
  108. _itemContainerGenerator = (IRecyclingItemContainerGenerator)base.ItemContainerGenerator;
  109. }
  110. return _itemContainerGenerator;
  111. }
  112. }
  113. private IRecyclingItemContainerGenerator _itemContainerGenerator;
  114. public double ExtentWidth => Extent.Width;
  115. public double ExtentHeight => Extent.Height;
  116. protected Size Extent { get; private set; } = new Size(0, 0);
  117. public double HorizontalOffset => Offset.X;
  118. public double VerticalOffset => Offset.Y;
  119. protected Size Viewport { get; private set; } = new Size(0, 0);
  120. public double ViewportWidth => Viewport.Width;
  121. public double ViewportHeight => Viewport.Height;
  122. protected Point Offset { get; private set; } = new Point(0, 0);
  123. /// <summary>
  124. /// The range of items that a realized in viewport or cache.
  125. /// </summary>
  126. protected ItemRange ItemRange { get; set; }
  127. public ScrollViewer ScrollOwner { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
  128. public DependencyObject ItemsOwner1 { get => _itemsOwner; set => _itemsOwner = value; }
  129. private Visibility previousVerticalScrollBarVisibility = Visibility.Collapsed;
  130. private Visibility previousHorizontalScrollBarVisibility = Visibility.Collapsed;
  131. protected virtual void UpdateScrollInfo(Size availableSize, Size extent)
  132. {
  133. bool invalidateScrollInfo = false;
  134. if (extent != Extent)
  135. {
  136. Extent = extent;
  137. invalidateScrollInfo = true;
  138. }
  139. if (availableSize != Viewport)
  140. {
  141. Viewport = availableSize;
  142. invalidateScrollInfo = true;
  143. }
  144. if (ViewportHeight != 0 && VerticalOffset != 0 && VerticalOffset + ViewportHeight + 1 >= ExtentHeight)
  145. {
  146. Offset = new Point(Offset.X, extent.Height - availableSize.Height);
  147. invalidateScrollInfo = true;
  148. }
  149. if (ViewportWidth != 0 && HorizontalOffset != 0 && HorizontalOffset + ViewportWidth + 1 >= ExtentWidth)
  150. {
  151. Offset = new Point(extent.Width - availableSize.Width, Offset.Y);
  152. invalidateScrollInfo = true;
  153. }
  154. if (invalidateScrollInfo)
  155. {
  156. GetScrollOwner()?.InvalidateScrollInfo();
  157. }
  158. }
  159. public virtual Rect MakeVisible(Visual visual, Rect rectangle)
  160. {
  161. Point pos = visual.TransformToAncestor(this).Transform(Offset);
  162. double scrollAmountX = 0;
  163. double scrollAmountY = 0;
  164. if (pos.X < Offset.X)
  165. {
  166. scrollAmountX = -(Offset.X - pos.X);
  167. }
  168. else if ((pos.X + rectangle.Width) > (Offset.X + Viewport.Width))
  169. {
  170. double notVisibleX = (pos.X + rectangle.Width) - (Offset.X + Viewport.Width);
  171. double maxScrollX = pos.X - Offset.X; // keep left of the visual visible
  172. scrollAmountX = Math.Min(notVisibleX, maxScrollX);
  173. }
  174. if (pos.Y < Offset.Y)
  175. {
  176. scrollAmountY = -(Offset.Y - pos.Y);
  177. }
  178. else if ((pos.Y + rectangle.Height) > (Offset.Y + Viewport.Height))
  179. {
  180. double notVisibleY = (pos.Y + rectangle.Height) - (Offset.Y + Viewport.Height);
  181. double maxScrollY = pos.Y - Offset.Y; // keep top of the visual visible
  182. scrollAmountY = Math.Min(notVisibleY, maxScrollY);
  183. }
  184. SetHorizontalOffset(Offset.X + scrollAmountX);
  185. SetVerticalOffset(Offset.Y + scrollAmountY);
  186. double visibleRectWidth = Math.Min(rectangle.Width, Viewport.Width);
  187. double visibleRectHeight = Math.Min(rectangle.Height, Viewport.Height);
  188. return new Rect(scrollAmountX, scrollAmountY, visibleRectWidth, visibleRectHeight);
  189. }
  190. protected override void OnItemsChanged(object sender, ItemsChangedEventArgs args)
  191. {
  192. switch (args.Action)
  193. {
  194. case NotifyCollectionChangedAction.Remove:
  195. case NotifyCollectionChangedAction.Replace:
  196. RemoveInternalChildRange(args.Position.Index, args.ItemUICount);
  197. break;
  198. case NotifyCollectionChangedAction.Move:
  199. RemoveInternalChildRange(args.OldPosition.Index, args.ItemUICount);
  200. break;
  201. }
  202. }
  203. protected int GetItemIndexFromChildIndex(int childIndex)
  204. {
  205. var generatorPosition = GetGeneratorPositionFromChildIndex(childIndex);
  206. return ItemContainerGenerator.IndexFromGeneratorPosition(generatorPosition);
  207. }
  208. protected virtual GeneratorPosition GetGeneratorPositionFromChildIndex(int childIndex)
  209. {
  210. return new GeneratorPosition(childIndex, 0);
  211. }
  212. protected override Size MeasureOverride(Size availableSize)
  213. {
  214. /* Sometimes when scrolling the scrollbar gets hidden without any reason. In this case the "IsMeasureValid"
  215. * property of the ScrollOwner is false. To prevent a infinite circle the mesasure call is ignored. */
  216. if (GetScrollOwner() != null)
  217. {
  218. bool verticalScrollBarGotHidden = GetScrollOwner().VerticalScrollBarVisibility == ScrollBarVisibility.Auto
  219. && GetScrollOwner().ComputedVerticalScrollBarVisibility != Visibility.Visible
  220. && GetScrollOwner().ComputedVerticalScrollBarVisibility != previousVerticalScrollBarVisibility;
  221. bool horizontalScrollBarGotHidden = GetScrollOwner().HorizontalScrollBarVisibility == ScrollBarVisibility.Auto
  222. && GetScrollOwner().ComputedHorizontalScrollBarVisibility != Visibility.Visible
  223. && GetScrollOwner().ComputedHorizontalScrollBarVisibility != previousHorizontalScrollBarVisibility;
  224. previousVerticalScrollBarVisibility = GetScrollOwner().ComputedVerticalScrollBarVisibility;
  225. previousHorizontalScrollBarVisibility = GetScrollOwner().ComputedHorizontalScrollBarVisibility;
  226. if (!GetScrollOwner().IsMeasureValid && verticalScrollBarGotHidden || horizontalScrollBarGotHidden)
  227. {
  228. return availableSize;
  229. }
  230. }
  231. var groupItem = ItemsOwner as IHierarchicalVirtualizationAndScrollInfo;
  232. Size extent;
  233. Size desiredSize;
  234. if (groupItem != null)
  235. {
  236. /* If the ItemsOwner is a group item the availableSize is ifinity.
  237. * Therfore the vieport size provided by the group item is used. */
  238. var viewportSize = groupItem.Constraints.Viewport.Size;
  239. var headerSize = groupItem.HeaderDesiredSizes.PixelSize;
  240. double availableWidth = Math.Max(viewportSize.Width - 5, 0); // left margin of 5 dp
  241. double availableHeight = Math.Max(viewportSize.Height - headerSize.Height, 0);
  242. availableSize = new Size(availableWidth, availableHeight);
  243. extent = CalculateExtent(availableSize);
  244. desiredSize = new Size(extent.Width, extent.Height);
  245. Extent = extent;
  246. Offset = groupItem.Constraints.Viewport.Location;
  247. Viewport = groupItem.Constraints.Viewport.Size;
  248. CacheLength = groupItem.Constraints.CacheLength;
  249. CacheLengthUnit = groupItem.Constraints.CacheLengthUnit; // can be Item or Pixel
  250. }
  251. else
  252. {
  253. extent = CalculateExtent(availableSize);
  254. double desiredWidth = Math.Min(availableSize.Width, extent.Width);
  255. double desiredHeight = Math.Min(availableSize.Height, extent.Height);
  256. desiredSize = new Size(desiredWidth, desiredHeight);
  257. UpdateScrollInfo(desiredSize, extent);
  258. CacheLength = GetCacheLength(ItemsOwner);
  259. CacheLengthUnit = GetCacheLengthUnit(ItemsOwner); // can be Page, Item or Pixel
  260. }
  261. ItemRange = UpdateItemRange();
  262. RealizeItems();
  263. VirtualizeItems();
  264. return desiredSize;
  265. }
  266. /// <summary>
  267. /// Realizes visible and cached items.
  268. /// </summary>
  269. protected virtual void RealizeItems()
  270. {
  271. var startPosition = ItemContainerGenerator.GeneratorPositionFromIndex(ItemRange.StartIndex);
  272. int childIndex = startPosition.Offset == 0 ? startPosition.Index : startPosition.Index + 1;
  273. using (ItemContainerGenerator.StartAt(startPosition, GeneratorDirection.Forward, true))
  274. {
  275. for (int i = ItemRange.StartIndex; i <= ItemRange.EndIndex; i++, childIndex++)
  276. {
  277. UIElement child = (UIElement)ItemContainerGenerator.GenerateNext(out bool isNewlyRealized);
  278. if (isNewlyRealized || /*recycled*/!InternalChildren.Contains(child))
  279. {
  280. if (childIndex >= InternalChildren.Count)
  281. {
  282. AddInternalChild(child);
  283. }
  284. else
  285. {
  286. InsertInternalChild(childIndex, child);
  287. }
  288. ItemContainerGenerator.PrepareItemContainer(child);
  289. child.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
  290. }
  291. if (child is IHierarchicalVirtualizationAndScrollInfo groupItem)
  292. {
  293. groupItem.Constraints = new HierarchicalVirtualizationConstraints(
  294. new VirtualizationCacheLength(0),
  295. VirtualizationCacheLengthUnit.Item,
  296. new Rect(0, 0, ViewportWidth, ViewportHeight));
  297. child.Measure(new Size(ViewportWidth, ViewportHeight));
  298. }
  299. }
  300. }
  301. }
  302. /// <summary>
  303. /// Virtualizes (cleanups) no longer visible or cached items.
  304. /// </summary>
  305. protected virtual void VirtualizeItems()
  306. {
  307. for (int childIndex = InternalChildren.Count - 1; childIndex >= 0; childIndex--)
  308. {
  309. var generatorPosition = GetGeneratorPositionFromChildIndex(childIndex);
  310. int itemIndex = ItemContainerGenerator.IndexFromGeneratorPosition(generatorPosition);
  311. if (itemIndex != -1 && !ItemRange.Contains(itemIndex))
  312. {
  313. if (VirtualizationMode == VirtualizationMode.Recycling)
  314. {
  315. ItemContainerGenerator.Recycle(generatorPosition, 1);
  316. }
  317. else
  318. {
  319. ItemContainerGenerator.Remove(generatorPosition, 1);
  320. }
  321. RemoveInternalChildRange(childIndex, 1);
  322. }
  323. }
  324. }
  325. /// <summary>
  326. /// Calculates the extent that would be needed to show all items.
  327. /// </summary>
  328. protected abstract Size CalculateExtent(Size availableSize);
  329. /// <summary>
  330. /// Calculates the item range that is visible in the viewport or cached.
  331. /// </summary>
  332. protected abstract ItemRange UpdateItemRange();
  333. public void SetVerticalOffset(double offset)
  334. {
  335. if (offset < 0 || Viewport.Height >= Extent.Height)
  336. {
  337. offset = 0;
  338. }
  339. else if (offset + Viewport.Height >= Extent.Height)
  340. {
  341. offset = Extent.Height - Viewport.Height;
  342. }
  343. Offset = new Point(Offset.X, offset);
  344. GetScrollOwner()?.InvalidateScrollInfo();
  345. InvalidateMeasure();
  346. }
  347. public void SetHorizontalOffset(double offset)
  348. {
  349. if (offset < 0 || Viewport.Width >= Extent.Width)
  350. {
  351. offset = 0;
  352. }
  353. else if (offset + Viewport.Width >= Extent.Width)
  354. {
  355. offset = Extent.Width - Viewport.Width;
  356. }
  357. Offset = new Point(offset, Offset.Y);
  358. GetScrollOwner()?.InvalidateScrollInfo();
  359. InvalidateMeasure();
  360. }
  361. protected void ScrollVertical(double amount)
  362. {
  363. SetVerticalOffset(VerticalOffset + amount);
  364. }
  365. protected void ScrollHorizontal(double amount)
  366. {
  367. SetHorizontalOffset(HorizontalOffset + amount);
  368. }
  369. public void LineUp() => ScrollVertical(ScrollUnit == ScrollUnit.Pixel ? -ScrollLineDelta : GetLineUpScrollAmount());
  370. public void LineDown() => ScrollVertical(ScrollUnit == ScrollUnit.Pixel ? ScrollLineDelta : GetLineDownScrollAmount());
  371. public void LineLeft() => ScrollHorizontal(ScrollUnit == ScrollUnit.Pixel ? -ScrollLineDelta : GetLineLeftScrollAmount());
  372. public void LineRight() => ScrollHorizontal(ScrollUnit == ScrollUnit.Pixel ? ScrollLineDelta : GetLineRightScrollAmount());
  373. public void MouseWheelUp()
  374. {
  375. if (MouseWheelScrollDirection == ScrollDirection.Vertical)
  376. {
  377. ScrollVertical(ScrollUnit == ScrollUnit.Pixel ? -MouseWheelDelta : GetMouseWheelUpScrollAmount());
  378. }
  379. else
  380. {
  381. MouseWheelLeft();
  382. }
  383. }
  384. public void MouseWheelDown()
  385. {
  386. if (MouseWheelScrollDirection == ScrollDirection.Vertical)
  387. {
  388. ScrollVertical(ScrollUnit == ScrollUnit.Pixel ? MouseWheelDelta : GetMouseWheelDownScrollAmount());
  389. }
  390. else
  391. {
  392. MouseWheelRight();
  393. }
  394. }
  395. public void MouseWheelLeft() => ScrollHorizontal(ScrollUnit == ScrollUnit.Pixel ? -MouseWheelDelta : GetMouseWheelLeftScrollAmount());
  396. public void MouseWheelRight() => ScrollHorizontal(ScrollUnit == ScrollUnit.Pixel ? MouseWheelDelta : GetMouseWheelRightScrollAmount());
  397. public void PageUp() => ScrollVertical(ScrollUnit == ScrollUnit.Pixel ? -ViewportHeight : GetPageUpScrollAmount());
  398. public void PageDown() => ScrollVertical(ScrollUnit == ScrollUnit.Pixel ? ViewportHeight : GetPageDownScrollAmount());
  399. public void PageLeft() => ScrollHorizontal(ScrollUnit == ScrollUnit.Pixel ? -ViewportHeight : GetPageLeftScrollAmount());
  400. public void PageRight() => ScrollHorizontal(ScrollUnit == ScrollUnit.Pixel ? ViewportHeight : GetPageRightScrollAmount());
  401. protected abstract double GetLineUpScrollAmount();
  402. protected abstract double GetLineDownScrollAmount();
  403. protected abstract double GetLineLeftScrollAmount();
  404. protected abstract double GetLineRightScrollAmount();
  405. protected abstract double GetMouseWheelUpScrollAmount();
  406. protected abstract double GetMouseWheelDownScrollAmount();
  407. protected abstract double GetMouseWheelLeftScrollAmount();
  408. protected abstract double GetMouseWheelRightScrollAmount();
  409. protected abstract double GetPageUpScrollAmount();
  410. protected abstract double GetPageDownScrollAmount();
  411. protected abstract double GetPageLeftScrollAmount();
  412. protected abstract double GetPageRightScrollAmount();
  413. }
  414. }