ContentPresenter.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450
  1. // Copyright (c) The Avalonia Project. All rights reserved.
  2. // Licensed under the MIT license. See licence.md file in the project root for full license information.
  3. using System;
  4. using Avalonia.Controls.Primitives;
  5. using Avalonia.Controls.Templates;
  6. using Avalonia.Controls.Utils;
  7. using Avalonia.Layout;
  8. using Avalonia.LogicalTree;
  9. using Avalonia.Media;
  10. using Avalonia.Metadata;
  11. namespace Avalonia.Controls.Presenters
  12. {
  13. /// <summary>
  14. /// Presents a single item of data inside a <see cref="TemplatedControl"/> template.
  15. /// </summary>
  16. public class ContentPresenter : Control, IContentPresenter
  17. {
  18. /// <summary>
  19. /// Defines the <see cref="Background"/> property.
  20. /// </summary>
  21. public static readonly StyledProperty<IBrush> BackgroundProperty =
  22. Border.BackgroundProperty.AddOwner<ContentPresenter>();
  23. /// <summary>
  24. /// Defines the <see cref="BorderBrush"/> property.
  25. /// </summary>
  26. public static readonly AvaloniaProperty<IBrush> BorderBrushProperty =
  27. Border.BorderBrushProperty.AddOwner<ContentPresenter>();
  28. /// <summary>
  29. /// Defines the <see cref="BorderThickness"/> property.
  30. /// </summary>
  31. public static readonly StyledProperty<Thickness> BorderThicknessProperty =
  32. Border.BorderThicknessProperty.AddOwner<ContentPresenter>();
  33. /// <summary>
  34. /// Defines the <see cref="Child"/> property.
  35. /// </summary>
  36. public static readonly DirectProperty<ContentPresenter, IControl> ChildProperty =
  37. AvaloniaProperty.RegisterDirect<ContentPresenter, IControl>(
  38. nameof(Child),
  39. o => o.Child);
  40. /// <summary>
  41. /// Defines the <see cref="Content"/> property.
  42. /// </summary>
  43. public static readonly StyledProperty<object> ContentProperty =
  44. ContentControl.ContentProperty.AddOwner<ContentPresenter>();
  45. /// <summary>
  46. /// Defines the <see cref="ContentTemplate"/> property.
  47. /// </summary>
  48. public static readonly StyledProperty<IDataTemplate> ContentTemplateProperty =
  49. ContentControl.ContentTemplateProperty.AddOwner<ContentPresenter>();
  50. /// <summary>
  51. /// Defines the <see cref="CornerRadius"/> property.
  52. /// </summary>
  53. public static readonly StyledProperty<CornerRadius> CornerRadiusProperty =
  54. Border.CornerRadiusProperty.AddOwner<ContentPresenter>();
  55. /// <summary>
  56. /// Defines the <see cref="HorizontalContentAlignment"/> property.
  57. /// </summary>
  58. public static readonly StyledProperty<HorizontalAlignment> HorizontalContentAlignmentProperty =
  59. ContentControl.HorizontalContentAlignmentProperty.AddOwner<ContentPresenter>();
  60. /// <summary>
  61. /// Defines the <see cref="VerticalContentAlignment"/> property.
  62. /// </summary>
  63. public static readonly StyledProperty<VerticalAlignment> VerticalContentAlignmentProperty =
  64. ContentControl.VerticalContentAlignmentProperty.AddOwner<ContentPresenter>();
  65. /// <summary>
  66. /// Defines the <see cref="Padding"/> property.
  67. /// </summary>
  68. public static readonly StyledProperty<Thickness> PaddingProperty =
  69. Decorator.PaddingProperty.AddOwner<ContentPresenter>();
  70. private IControl _child;
  71. private bool _createdChild;
  72. private IDataTemplate _dataTemplate;
  73. private readonly BorderRenderHelper _borderRenderer = new BorderRenderHelper();
  74. /// <summary>
  75. /// Initializes static members of the <see cref="ContentPresenter"/> class.
  76. /// </summary>
  77. static ContentPresenter()
  78. {
  79. ContentProperty.Changed.AddClassHandler<ContentPresenter>(x => x.ContentChanged);
  80. ContentTemplateProperty.Changed.AddClassHandler<ContentPresenter>(x => x.ContentChanged);
  81. TemplatedParentProperty.Changed.AddClassHandler<ContentPresenter>(x => x.TemplatedParentChanged);
  82. }
  83. /// <summary>
  84. /// Initializes a new instance of the <see cref="ContentPresenter"/> class.
  85. /// </summary>
  86. public ContentPresenter()
  87. {
  88. }
  89. /// <summary>
  90. /// Gets or sets a brush with which to paint the background.
  91. /// </summary>
  92. public IBrush Background
  93. {
  94. get { return GetValue(BackgroundProperty); }
  95. set { SetValue(BackgroundProperty, value); }
  96. }
  97. /// <summary>
  98. /// Gets or sets a brush with which to paint the border.
  99. /// </summary>
  100. public IBrush BorderBrush
  101. {
  102. get { return GetValue(BorderBrushProperty); }
  103. set { SetValue(BorderBrushProperty, value); }
  104. }
  105. /// <summary>
  106. /// Gets or sets the thickness of the border.
  107. /// </summary>
  108. public Thickness BorderThickness
  109. {
  110. get { return GetValue(BorderThicknessProperty); }
  111. set { SetValue(BorderThicknessProperty, value); }
  112. }
  113. /// <summary>
  114. /// Gets the control displayed by the presenter.
  115. /// </summary>
  116. public IControl Child
  117. {
  118. get { return _child; }
  119. private set { SetAndRaise(ChildProperty, ref _child, value); }
  120. }
  121. /// <summary>
  122. /// Gets or sets the content to be displayed by the presenter.
  123. /// </summary>
  124. [DependsOn(nameof(ContentTemplate))]
  125. public object Content
  126. {
  127. get { return GetValue(ContentProperty); }
  128. set { SetValue(ContentProperty, value); }
  129. }
  130. /// <summary>
  131. /// Gets or sets the data template used to display the content of the control.
  132. /// </summary>
  133. public IDataTemplate ContentTemplate
  134. {
  135. get { return GetValue(ContentTemplateProperty); }
  136. set { SetValue(ContentTemplateProperty, value); }
  137. }
  138. /// <summary>
  139. /// Gets or sets the radius of the border rounded corners.
  140. /// </summary>
  141. public CornerRadius CornerRadius
  142. {
  143. get { return GetValue(CornerRadiusProperty); }
  144. set { SetValue(CornerRadiusProperty, value); }
  145. }
  146. /// <summary>
  147. /// Gets or sets the horizontal alignment of the content within the control.
  148. /// </summary>
  149. public HorizontalAlignment HorizontalContentAlignment
  150. {
  151. get { return GetValue(HorizontalContentAlignmentProperty); }
  152. set { SetValue(HorizontalContentAlignmentProperty, value); }
  153. }
  154. /// <summary>
  155. /// Gets or sets the vertical alignment of the content within the control.
  156. /// </summary>
  157. public VerticalAlignment VerticalContentAlignment
  158. {
  159. get { return GetValue(VerticalContentAlignmentProperty); }
  160. set { SetValue(VerticalContentAlignmentProperty, value); }
  161. }
  162. /// <summary>
  163. /// Gets or sets the padding to place around the <see cref="Child"/> control.
  164. /// </summary>
  165. public Thickness Padding
  166. {
  167. get { return GetValue(PaddingProperty); }
  168. set { SetValue(PaddingProperty, value); }
  169. }
  170. /// <inheritdoc/>
  171. public override sealed void ApplyTemplate()
  172. {
  173. if (!_createdChild && ((ILogical)this).IsAttachedToLogicalTree)
  174. {
  175. UpdateChild();
  176. }
  177. }
  178. /// <inheritdoc/>
  179. protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
  180. {
  181. base.OnAttachedToVisualTree(e);
  182. _dataTemplate = null;
  183. }
  184. /// <summary>
  185. /// Updates the <see cref="Child"/> control based on the control's <see cref="Content"/>.
  186. /// </summary>
  187. /// <remarks>
  188. /// Usually the <see cref="Child"/> control is created automatically when
  189. /// <see cref="ApplyTemplate"/> is called; however for this to happen, the control needs to
  190. /// be attached to a logical tree (if the control is not attached to the logical tree, it
  191. /// is reasonable to expect that the DataTemplates needed for the child are not yet
  192. /// available). This method forces the <see cref="Child"/> control's creation at any point,
  193. /// and is particularly useful in unit tests.
  194. /// </remarks>
  195. public void UpdateChild()
  196. {
  197. var content = Content;
  198. var oldChild = Child;
  199. var newChild = CreateChild();
  200. // Remove the old child if we're not recycling it.
  201. if (oldChild != null && newChild != oldChild)
  202. {
  203. VisualChildren.Remove(oldChild);
  204. }
  205. // Set the DataContext if the data isn't a control.
  206. if (!(content is IControl))
  207. {
  208. DataContext = content;
  209. }
  210. else
  211. {
  212. ClearValue(DataContextProperty);
  213. }
  214. // Update the Child.
  215. if (newChild == null)
  216. {
  217. Child = null;
  218. }
  219. else if (newChild != oldChild)
  220. {
  221. ((ISetInheritanceParent)newChild).SetParent(this);
  222. Child = newChild;
  223. if (oldChild?.Parent == this)
  224. {
  225. LogicalChildren.Remove(oldChild);
  226. }
  227. if (newChild.Parent == null && TemplatedParent == null)
  228. {
  229. LogicalChildren.Add(newChild);
  230. }
  231. VisualChildren.Add(newChild);
  232. }
  233. _createdChild = true;
  234. }
  235. /// <inheritdoc/>
  236. protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
  237. {
  238. base.OnAttachedToLogicalTree(e);
  239. _createdChild = false;
  240. InvalidateMeasure();
  241. }
  242. /// <inheritdoc/>
  243. public override void Render(DrawingContext context)
  244. {
  245. _borderRenderer.Render(context, Bounds.Size, BorderThickness, CornerRadius, Background, BorderBrush);
  246. }
  247. /// <summary>
  248. /// Creates the child control.
  249. /// </summary>
  250. /// <returns>The child control or null.</returns>
  251. protected virtual IControl CreateChild()
  252. {
  253. var content = Content;
  254. var oldChild = Child;
  255. var newChild = content as IControl;
  256. if (content != null && newChild == null)
  257. {
  258. var dataTemplate = this.FindDataTemplate(content, ContentTemplate) ?? FuncDataTemplate.Default;
  259. // We have content and it isn't a control, so if the new data template is the same
  260. // as the old data template, try to recycle the existing child control to display
  261. // the new data.
  262. if (dataTemplate == _dataTemplate && dataTemplate.SupportsRecycling)
  263. {
  264. newChild = oldChild;
  265. }
  266. else
  267. {
  268. _dataTemplate = dataTemplate;
  269. newChild = _dataTemplate.Build(content);
  270. // Give the new control its own name scope.
  271. if (newChild is Control controlResult)
  272. {
  273. NameScope.SetNameScope(controlResult, new NameScope());
  274. }
  275. }
  276. }
  277. else
  278. {
  279. _dataTemplate = null;
  280. }
  281. return newChild;
  282. }
  283. /// <inheritdoc/>
  284. protected override Size MeasureOverride(Size availableSize)
  285. {
  286. return Border.MeasureOverrideImpl(availableSize, Child, Padding, BorderThickness);
  287. }
  288. /// <inheritdoc/>
  289. protected override Size ArrangeOverride(Size finalSize)
  290. {
  291. finalSize = ArrangeOverrideImpl(finalSize, new Vector());
  292. _borderRenderer.Update(finalSize, BorderThickness, CornerRadius);
  293. return finalSize;
  294. }
  295. /// <summary>
  296. /// Called when the <see cref="Content"/> property changes.
  297. /// </summary>
  298. /// <param name="e">The event args.</param>
  299. private void ContentChanged(AvaloniaPropertyChangedEventArgs e)
  300. {
  301. _createdChild = false;
  302. if (((ILogical)this).IsAttachedToLogicalTree)
  303. {
  304. UpdateChild();
  305. }
  306. else if (Child != null)
  307. {
  308. VisualChildren.Remove(Child);
  309. LogicalChildren.Remove(Child);
  310. Child = null;
  311. _dataTemplate = null;
  312. }
  313. InvalidateMeasure();
  314. }
  315. internal Size ArrangeOverrideImpl(Size finalSize, Vector offset)
  316. {
  317. if (Child == null) return finalSize;
  318. var padding = Padding;
  319. var borderThickness = BorderThickness;
  320. var horizontalContentAlignment = HorizontalContentAlignment;
  321. var verticalContentAlignment = VerticalContentAlignment;
  322. var useLayoutRounding = UseLayoutRounding;
  323. var availableSizeMinusMargins = new Size(
  324. Math.Max(0, finalSize.Width - padding.Left - padding.Right - borderThickness.Left - borderThickness.Right),
  325. Math.Max(0, finalSize.Height - padding.Top - padding.Bottom - borderThickness.Top - borderThickness.Bottom));
  326. var size = availableSizeMinusMargins;
  327. var scale = GetLayoutScale();
  328. var originX = offset.X + padding.Left + borderThickness.Left;
  329. var originY = offset.Y + padding.Top + borderThickness.Top;
  330. if (horizontalContentAlignment != HorizontalAlignment.Stretch)
  331. {
  332. size = size.WithWidth(Math.Min(size.Width, DesiredSize.Width - padding.Left - padding.Right));
  333. }
  334. if (verticalContentAlignment != VerticalAlignment.Stretch)
  335. {
  336. size = size.WithHeight(Math.Min(size.Height, DesiredSize.Height - padding.Top - padding.Bottom));
  337. }
  338. if (useLayoutRounding)
  339. {
  340. size = new Size(
  341. Math.Ceiling(size.Width * scale) / scale,
  342. Math.Ceiling(size.Height * scale) / scale);
  343. availableSizeMinusMargins = new Size(
  344. Math.Ceiling(availableSizeMinusMargins.Width * scale) / scale,
  345. Math.Ceiling(availableSizeMinusMargins.Height * scale) / scale);
  346. }
  347. switch (horizontalContentAlignment)
  348. {
  349. case HorizontalAlignment.Center:
  350. originX += (availableSizeMinusMargins.Width - size.Width) / 2;
  351. break;
  352. case HorizontalAlignment.Right:
  353. originX += availableSizeMinusMargins.Width - size.Width;
  354. break;
  355. }
  356. switch (verticalContentAlignment)
  357. {
  358. case VerticalAlignment.Center:
  359. originY += (availableSizeMinusMargins.Height - size.Height) / 2;
  360. break;
  361. case VerticalAlignment.Bottom:
  362. originY += availableSizeMinusMargins.Height - size.Height;
  363. break;
  364. }
  365. if (useLayoutRounding)
  366. {
  367. originX = Math.Floor(originX * scale) / scale;
  368. originY = Math.Floor(originY * scale) / scale;
  369. }
  370. Child.Arrange(new Rect(originX, originY, size.Width, size.Height));
  371. return finalSize;
  372. }
  373. private double GetLayoutScale()
  374. {
  375. var result = (VisualRoot as ILayoutRoot)?.LayoutScaling ?? 1.0;
  376. if (result == 0 || double.IsNaN(result) || double.IsInfinity(result))
  377. {
  378. throw new Exception($"Invalid LayoutScaling returned from {VisualRoot.GetType()}");
  379. }
  380. return result;
  381. }
  382. private void TemplatedParentChanged(AvaloniaPropertyChangedEventArgs e)
  383. {
  384. (e.NewValue as IContentPresenterHost)?.RegisterContentPresenter(this);
  385. }
  386. }
  387. }