TestScrollable.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. using System;
  2. using Avalonia;
  3. using Avalonia.Controls;
  4. using Avalonia.Controls.Primitives;
  5. using Avalonia.Media;
  6. using Avalonia.VisualTree;
  7. namespace XamlTestApplication
  8. {
  9. public class TestScrollable : Control, ILogicalScrollable
  10. {
  11. private int itemCount = 100;
  12. private Size _extent;
  13. private Vector _offset;
  14. private Size _viewport;
  15. private Size _lineSize;
  16. public bool IsLogicalScrollEnabled => true;
  17. public Action InvalidateScroll { get; set; }
  18. Size ILogicalScrollable.Extent
  19. {
  20. get { return _extent; }
  21. }
  22. Vector ILogicalScrollable.Offset
  23. {
  24. get { return _offset; }
  25. set
  26. {
  27. _offset = value;
  28. InvalidateVisual();
  29. }
  30. }
  31. Size ILogicalScrollable.Viewport
  32. {
  33. get { return _viewport; }
  34. }
  35. public Size ScrollSize
  36. {
  37. get
  38. {
  39. return new Size(double.PositiveInfinity, 1);
  40. }
  41. }
  42. public Size PageScrollSize
  43. {
  44. get
  45. {
  46. return new Size(double.PositiveInfinity, Bounds.Height);
  47. }
  48. }
  49. public override void Render(DrawingContext context)
  50. {
  51. var y = 0.0;
  52. for (var i = (int)_offset.Y; i < itemCount; ++i)
  53. {
  54. using (var line = new FormattedText(
  55. "Item " + (i + 1),
  56. TextBlock.GetFontFamily(this),
  57. TextBlock.GetFontSize(this),
  58. TextBlock.GetFontStyle(this),
  59. TextAlignment.Left,
  60. TextBlock.GetFontWeight(this)))
  61. {
  62. context.DrawText(Brushes.Black, new Point(-_offset.X, y), line);
  63. y += _lineSize.Height;
  64. }
  65. }
  66. }
  67. public bool BringIntoView(IVisual target, Rect targetRect)
  68. {
  69. throw new NotImplementedException();
  70. }
  71. protected override Size MeasureOverride(Size availableSize)
  72. {
  73. using (var line = new FormattedText(
  74. "Item 100",
  75. TextBlock.GetFontFamily(this),
  76. TextBlock.GetFontSize(this),
  77. TextBlock.GetFontStyle(this),
  78. TextAlignment.Left,
  79. TextBlock.GetFontWeight(this)))
  80. {
  81. line.Constraint = availableSize;
  82. _lineSize = line.Measure();
  83. return new Size(_lineSize.Width, _lineSize.Height * itemCount);
  84. }
  85. }
  86. protected override Size ArrangeOverride(Size finalSize)
  87. {
  88. _viewport = new Size(finalSize.Width, finalSize.Height / _lineSize.Height);
  89. _extent = new Size(_lineSize.Width, itemCount + 1);
  90. InvalidateScroll?.Invoke();
  91. return finalSize;
  92. }
  93. }
  94. }