C#   发布时间:2022-04-03  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了c# – 如何创建包含(并显示)其他UIElements作为子项的自定义UIElement派生类?大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
假设我想创建一个直接从UIElement继承的类,并且能够包含一个或多个[外部添加的] UIElements作为子项 – 比如Panels和其他容器控件.很容易让班级以某种形式或其他形式收集UIElements,但我如何让它们与我的班级一起展示/呈现?

我认为它们必须以某种方式作为我自己的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
}

大佬总结

以上是大佬教程为你收集整理的c# – 如何创建包含(并显示)其他UIElements作为子项的自定义UIElement派生类?全部内容,希望文章能够帮你解决c# – 如何创建包含(并显示)其他UIElements作为子项的自定义UIElement派生类?所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。