VirtualizingPanelBase.cs 21 KB

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