gpt4 book ai didi

wpf - 自定义 UIElement 是否可以实现 IList 并直接分配子项(在 XAML 中)?

转载 作者:行者123 更新时间:2023-12-04 14:27:03 25 4
gpt4 key购买 nike

场景:我有一个自定义范围UIElements (事实上​​,我已经替换了所有标准的 WPF FrameworkElements 我将使用更轻、更高效的对应物)用于自定义布局系统,旨在仅使用这些。它们都继承自一个名为 Surface 的类。 (它又是 UIElement 的直系后代)。

我现在想知道我的 Panel 版本是否(我们称之为 SurfacePanel )可以简单地实现 IList<Surface>并允许 child Surface要直接添加到它的元素,而不是添加到 Children属性(与常规 WPF 面板一样),在 XAML .

为了说明 - 在代码隐藏中,我现在可以这样做:

SurfacePanel.Add(child);

从那开始,我希望能够在 XAML 中做到这一点:
<SurfacePanel>
<child />
</SurfacePanel>

但 XAML 似乎要求我有这样的代码隐藏模式:
SurfacePanel.Children.Add(child)

(我真的不需要这些控件来支持 XAML 在运行时环境中工作,但是在测试和原型(prototype)设计时,我喜欢让我的 UI 控件“对 XAML 友好”,这样我就可以从 VS 中的可视化设计器中受益(以及属性 Pane 等),如果只是作为“预览”窗口)。

由于我的控件继承自 UIElement (并具有适当的测量/排列/渲染覆盖等),它们在放置时运行良好,例如,常规 CanvasGrid .但是 VS XAML 解析器对我的 SurfacePanel 不太满意(实现 IList<Surface> )当我在标记中添加 child 时。它说“无法向“SurfacePanel”类型的对象添加内容”。

我知道如果我添加 Children适当类型的属性并将属性添加到 SurfaceCanvas类( [ContentProperty("Children")] ),它将起作用。但自从 SurfacePanel本身是一个能够做同样事情的集合,有没有办法让 XAML “得到它”?

编辑:

我可以通过添加 Children 来解决 XAML 的“合规性”问题。 SurfacePanel 上的属性(property)简单地返回它的内部 List ,但随后在其上添加和删除元素会直接绕过将子元素连接起来的内部逻辑。

如果内部列表是 ObservableCollection ,我可以按照常规方式进行接线,并在 CollectionChanged 中进行接线事件处理程序 - 但基本上是集成 IList 的全部要点直接在面板中是为了避免这种情况..

编辑2:

这“有效”(但绕过了接线):
[ContentProperty("Children")]
public class SurfacePanel : Surface, IList<Surface>
{
private readonly List<Surface> _children = new List<Surface>();

public List<Surface> Children
{
get { return _children; }
}
}

我无法返回 this因为 SurfacePanel不是 List<Surface> , 但一个 IList<Surface> .

如果我将属性更改为
    public IList<Surface> Children
{
get { return this; }
}

即使使用以下 XAML(但不使用 <m:SurfacePanel/> ),我也会收到错误消息:
<m:SurfacePanel>
</m:SurfacePanel>

错误信息是
Cannot set content property 'Children' on element 'SurfacePanel'. 'Children' has incorrect access level or its assembly does not allow access.

最佳答案

同时执行IList并声明 Children像这样的属性(property):

[ContentProperty("Children")]
public class SurfacePanel : Surface, IList, IList<Surface>
{
public IList Children
{
get { return this; }
}

...
}

关于wpf - 自定义 UIElement 是否可以实现 IList<UIElement> 并直接分配子项(在 XAML 中)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20525461/

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