ContentPresenter.cs 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  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 System.Reactive.Linq;
  5. using Avalonia.Controls.Primitives;
  6. using Avalonia.Controls.Templates;
  7. using Avalonia.Layout;
  8. using Avalonia.LogicalTree;
  9. using Avalonia.Media;
  10. using Avalonia.VisualTree;
  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<double> 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<float> 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. Border.PaddingProperty.AddOwner<ContentPresenter>();
  70. private IControl _child;
  71. private bool _createdChild;
  72. private IDataTemplate _dataTemplate;
  73. /// <summary>
  74. /// Initializes static members of the <see cref="ContentPresenter"/> class.
  75. /// </summary>
  76. static ContentPresenter()
  77. {
  78. ContentProperty.Changed.AddClassHandler<ContentPresenter>(x => x.ContentChanged);
  79. ContentTemplateProperty.Changed.AddClassHandler<ContentPresenter>(x => x.ContentChanged);
  80. TemplatedParentProperty.Changed.AddClassHandler<ContentPresenter>(x => x.TemplatedParentChanged);
  81. }
  82. /// <summary>
  83. /// Initializes a new instance of the <see cref="ContentPresenter"/> class.
  84. /// </summary>
  85. public ContentPresenter()
  86. {
  87. }
  88. /// <summary>
  89. /// Gets or sets a brush with which to paint the background.
  90. /// </summary>
  91. public IBrush Background
  92. {
  93. get { return GetValue(BackgroundProperty); }
  94. set { SetValue(BackgroundProperty, value); }
  95. }
  96. /// <summary>
  97. /// Gets or sets a brush with which to paint the border.
  98. /// </summary>
  99. public IBrush BorderBrush
  100. {
  101. get { return GetValue(BorderBrushProperty); }
  102. set { SetValue(BorderBrushProperty, value); }
  103. }
  104. /// <summary>
  105. /// Gets or sets the thickness of the border.
  106. /// </summary>
  107. public double BorderThickness
  108. {
  109. get { return GetValue(BorderThicknessProperty); }
  110. set { SetValue(BorderThicknessProperty, value); }
  111. }
  112. /// <summary>
  113. /// Gets the control displayed by the presenter.
  114. /// </summary>
  115. public IControl Child
  116. {
  117. get { return _child; }
  118. private set { SetAndRaise(ChildProperty, ref _child, value); }
  119. }
  120. /// <summary>
  121. /// Gets or sets the content to be displayed by the presenter.
  122. /// </summary>
  123. public object Content
  124. {
  125. get { return GetValue(ContentProperty); }
  126. set { SetValue(ContentProperty, value); }
  127. }
  128. /// <summary>
  129. /// Gets or sets the data template used to display the content of the control.
  130. /// </summary>
  131. public IDataTemplate ContentTemplate
  132. {
  133. get { return GetValue(ContentTemplateProperty); }
  134. set { SetValue(ContentTemplateProperty, value); }
  135. }
  136. /// <summary>
  137. /// Gets or sets the radius of the border rounded corners.
  138. /// </summary>
  139. public float CornerRadius
  140. {
  141. get { return GetValue(CornerRadiusProperty); }
  142. set { SetValue(CornerRadiusProperty, value); }
  143. }
  144. /// <summary>
  145. /// Gets or sets the horizontal alignment of the content within the control.
  146. /// </summary>
  147. public HorizontalAlignment HorizontalContentAlignment
  148. {
  149. get { return GetValue(HorizontalContentAlignmentProperty); }
  150. set { SetValue(HorizontalContentAlignmentProperty, value); }
  151. }
  152. /// <summary>
  153. /// Gets or sets the vertical alignment of the content within the control.
  154. /// </summary>
  155. public VerticalAlignment VerticalContentAlignment
  156. {
  157. get { return GetValue(VerticalContentAlignmentProperty); }
  158. set { SetValue(VerticalContentAlignmentProperty, value); }
  159. }
  160. /// <summary>
  161. /// Gets or sets the padding to place around the <see cref="Child"/> control.
  162. /// </summary>
  163. public Thickness Padding
  164. {
  165. get { return GetValue(PaddingProperty); }
  166. set { SetValue(PaddingProperty, value); }
  167. }
  168. /// <inheritdoc/>
  169. public override sealed void ApplyTemplate()
  170. {
  171. if (!_createdChild && ((ILogical)this).IsAttachedToLogicalTree)
  172. {
  173. UpdateChild();
  174. }
  175. }
  176. /// <inheritdoc/>
  177. protected override void OnAttachedToVisualTree(VisualTreeAttachmentEventArgs e)
  178. {
  179. base.OnAttachedToVisualTree(e);
  180. _dataTemplate = null;
  181. }
  182. /// <summary>
  183. /// Updates the <see cref="Child"/> control based on the control's <see cref="Content"/>.
  184. /// </summary>
  185. /// <remarks>
  186. /// Usually the <see cref="Child"/> control is created automatically when
  187. /// <see cref="ApplyTemplate"/> is called; however for this to happen, the control needs to
  188. /// be attached to a logical tree (if the control is not attached to the logical tree, it
  189. /// is reasonable to expect that the DataTemplates needed for the child are not yet
  190. /// available). This method forces the <see cref="Child"/> control's creation at any point,
  191. /// and is particularly useful in unit tests.
  192. /// </remarks>
  193. public void UpdateChild()
  194. {
  195. var content = Content;
  196. var oldChild = Child;
  197. var newChild = CreateChild();
  198. // Remove the old child if we're not recycling it.
  199. if (oldChild != null && newChild != oldChild)
  200. {
  201. VisualChildren.Remove(oldChild);
  202. }
  203. // Set the DataContext if the data isn't a control.
  204. if (!(content is IControl))
  205. {
  206. DataContext = content;
  207. }
  208. else
  209. {
  210. ClearValue(DataContextProperty);
  211. }
  212. // Update the Child.
  213. if (newChild == null)
  214. {
  215. Child = null;
  216. }
  217. else if (newChild != oldChild)
  218. {
  219. ((ISetInheritanceParent)newChild).SetParent(this);
  220. Child = newChild;
  221. if (oldChild?.Parent == this)
  222. {
  223. LogicalChildren.Remove(oldChild);
  224. }
  225. if (newChild.Parent == null)
  226. {
  227. var templatedLogicalParent = TemplatedParent as ILogical;
  228. if (templatedLogicalParent != null)
  229. {
  230. ((ISetLogicalParent)newChild).SetParent(templatedLogicalParent);
  231. }
  232. else
  233. {
  234. LogicalChildren.Add(newChild);
  235. }
  236. }
  237. VisualChildren.Add(newChild);
  238. }
  239. _createdChild = true;
  240. }
  241. /// <inheritdoc/>
  242. protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e)
  243. {
  244. base.OnAttachedToLogicalTree(e);
  245. _createdChild = false;
  246. InvalidateMeasure();
  247. }
  248. /// <inheritdoc/>
  249. public override void Render(DrawingContext context)
  250. {
  251. var background = Background;
  252. var borderBrush = BorderBrush;
  253. var borderThickness = BorderThickness;
  254. var cornerRadius = CornerRadius;
  255. var rect = new Rect(Bounds.Size).Deflate(BorderThickness);
  256. if (background != null)
  257. {
  258. context.FillRectangle(background, rect, cornerRadius);
  259. }
  260. if (borderBrush != null && borderThickness > 0)
  261. {
  262. context.DrawRectangle(new Pen(borderBrush, borderThickness), rect, cornerRadius);
  263. }
  264. }
  265. /// <summary>
  266. /// Creates the child control.
  267. /// </summary>
  268. /// <returns>The child control or null.</returns>
  269. protected virtual IControl CreateChild()
  270. {
  271. var content = Content;
  272. var oldChild = Child;
  273. var newChild = content as IControl;
  274. if (content != null && newChild == null)
  275. {
  276. var dataTemplate = this.FindDataTemplate(content, ContentTemplate) ?? FuncDataTemplate.Default;
  277. // We have content and it isn't a control, so if the new data template is the same
  278. // as the old data template, try to recycle the existing child control to display
  279. // the new data.
  280. if (dataTemplate == _dataTemplate && dataTemplate.SupportsRecycling)
  281. {
  282. newChild = oldChild;
  283. }
  284. else
  285. {
  286. _dataTemplate = dataTemplate;
  287. newChild = _dataTemplate.Build(content);
  288. // Give the new control its own name scope.
  289. if (newChild is Control controlResult)
  290. {
  291. NameScope.SetNameScope(controlResult, new NameScope());
  292. }
  293. }
  294. }
  295. else
  296. {
  297. _dataTemplate = null;
  298. }
  299. return newChild;
  300. }
  301. /// <inheritdoc/>
  302. protected override Size MeasureOverride(Size availableSize)
  303. {
  304. var child = Child;
  305. var padding = Padding + new Thickness(BorderThickness);
  306. if (child != null)
  307. {
  308. child.Measure(availableSize.Deflate(padding));
  309. return child.DesiredSize.Inflate(padding);
  310. }
  311. else
  312. {
  313. return new Size(padding.Left + padding.Right, padding.Bottom + padding.Top);
  314. }
  315. }
  316. /// <inheritdoc/>
  317. protected override Size ArrangeOverride(Size finalSize)
  318. {
  319. var child = Child;
  320. if (child != null)
  321. {
  322. var padding = Padding + new Thickness(BorderThickness);
  323. var sizeMinusPadding = finalSize.Deflate(padding);
  324. var size = sizeMinusPadding;
  325. var horizontalAlignment = HorizontalContentAlignment;
  326. var verticalAlignment = VerticalContentAlignment;
  327. var originX = padding.Left;
  328. var originY = padding.Top;
  329. if (horizontalAlignment != HorizontalAlignment.Stretch)
  330. {
  331. size = size.WithWidth(child.DesiredSize.Width);
  332. }
  333. if (verticalAlignment != VerticalAlignment.Stretch)
  334. {
  335. size = size.WithHeight(child.DesiredSize.Height);
  336. }
  337. switch (horizontalAlignment)
  338. {
  339. case HorizontalAlignment.Stretch:
  340. case HorizontalAlignment.Center:
  341. originX += (sizeMinusPadding.Width - size.Width) / 2;
  342. break;
  343. case HorizontalAlignment.Right:
  344. originX = size.Width - child.DesiredSize.Width;
  345. break;
  346. }
  347. switch (verticalAlignment)
  348. {
  349. case VerticalAlignment.Stretch:
  350. case VerticalAlignment.Center:
  351. originY += (sizeMinusPadding.Height - size.Height) / 2;
  352. break;
  353. case VerticalAlignment.Bottom:
  354. originY = size.Height - child.DesiredSize.Height;
  355. break;
  356. }
  357. child.Arrange(new Rect(originX, originY, size.Width, size.Height));
  358. }
  359. return finalSize;
  360. }
  361. /// <summary>
  362. /// Called when the <see cref="Content"/> property changes.
  363. /// </summary>
  364. /// <param name="e">The event args.</param>
  365. private void ContentChanged(AvaloniaPropertyChangedEventArgs e)
  366. {
  367. _createdChild = false;
  368. if (((ILogical)this).IsAttachedToLogicalTree)
  369. {
  370. UpdateChild();
  371. }
  372. else if (Child != null)
  373. {
  374. VisualChildren.Remove(Child);
  375. LogicalChildren.Remove(Child);
  376. Child = null;
  377. _dataTemplate = null;
  378. }
  379. InvalidateMeasure();
  380. }
  381. private void TemplatedParentChanged(AvaloniaPropertyChangedEventArgs e)
  382. {
  383. (e.NewValue as IContentPresenterHost)?.RegisterContentPresenter(this);
  384. }
  385. }
  386. }