[英]How can we make an class that contains multiple uielements and acts as a uielement
[英]How do I make a custom UIElement-derived class that contains (and displays) other UIElements as children?
假設我想創建一個直接從UIElement
繼承的類,並且能夠包含一個或多個[外部添加的] UIElement
作為子項 - 比如Panel
和其他容器控件。 很容易讓班級以某種形式存放UIElement
的集合,但是如何讓它們與我的班級一起展示/呈現呢?
我認為它們必須以某種方式作為我自己的UIElement
子項添加到可視化樹中(或者,可能通過VisualTreeHelper.GetDrawing
手動渲染它們並使用OnRender
的DrawingContext
渲染?但這看起來很笨拙)。
我不想知道我能-或者應該-從多個現成的控制繼承,像FrameworkElement
, Panel
, ContentControl
等等(如果有的話,我想知道他們是如何實現外部添加子元素的顯示/渲染,如適用)。
我有理由希望在層次結構中盡可能高,所以請不要給我任何講座,說明為什么XAML / WPF框架“符合”等等是件好事。
以下類在子元素的布局和呈現方面提供絕對最小值:
public class UIElementContainer : UIElement
{
private readonly UIElementCollection children;
public UIElementContainer()
{
children = new UIElementCollection(this, null);
}
public void AddChild(UIElement element)
{
children.Add(element);
}
public void RemoveChild(UIElement element)
{
children.Remove(element);
}
protected override int VisualChildrenCount
{
get { return children.Count; }
}
protected override Visual GetVisualChild(int index)
{
return children[index];
}
protected override Size MeasureCore(Size availableSize)
{
foreach (UIElement element in children)
{
element.Measure(availableSize);
}
return new Size();
}
protected override void ArrangeCore(Rect finalRect)
{
foreach (UIElement element in children)
{
element.Arrange(finalRect);
}
}
}
不需要具有UIElementCollection。 另一種實現可能如下所示:
public class UIElementContainer : UIElement
{
private readonly List<UIElement> children = new List<UIElement>();
public void AddChild(UIElement element)
{
children.Add(element);
AddVisualChild(element);
}
public void RemoveChild(UIElement element)
{
if (children.Remove(element))
{
RemoveVisualChild(element);
}
}
// plus the four overrides
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.