繁体   English   中英

如何创建包含(并显示)其他UIElements作为子项的自定义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手动渲染它们并使用OnRenderDrawingContext渲染?但这看起来很笨拙)。

不想知道我能-或者应该-从多个现成的控制继承,像FrameworkElementPanelContentControl等等(如果有的话,我想知道他们是如何实现外部添加子元素的显示/渲染,如适用)。

我有理由希望在层次结构中尽可能高,所以请不要给我任何讲座,说明为什么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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM