gpt4 book ai didi

c# - 如何创建包含(并显示)其他 UIElement 作为子元素的自定义 UIElement 派生类?

转载 作者:行者123 更新时间:2023-11-30 14:11:22 24 4
gpt4 key购买 nike

假设我想创建一个直接从 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
}

关于c# - 如何创建包含(并显示)其他 UIElement 作为子元素的自定义 UIElement 派生类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20338044/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com