gpt4 book ai didi

wpf - 如何解决 WPF 设计器错误 'The type {0} does not support direct content' .'?

转载 作者:行者123 更新时间:2023-12-04 12:26:08 26 4
gpt4 key购买 nike

以下 XAML(如下)在资源中定义了一个自定义集合,并尝试使用自定义对象填充它;

<UserControl x:Class="ImageListView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Width="300" Height="300"
xmlns:local="clr-namespace:MyControls" >
<UserControl.Resources>
<local:MyCustomCollection x:Key="MyKey">
<local:MyCustomItem>
</local:MyCustomItem>
</local:MyCustomCollection>
</UserControl.Resources>
</UserControl>

问题是我在“'MyCustomCollection'类型不支持直接内容'的设计器中收到错误。我已经尝试按照 MSDN 中的建议设置 ContentProperty,但无法弄清楚将其设置为什么。我使用的自定义集合对象在下面,非常简单。我已经尝试过 Item、Items 和 MyCustomItem,但想不出还有什么可以尝试的。
<ContentProperty("WhatGoesHere?")> _
Public Class MyCustomCollection
Inherits ObservableCollection(Of MyCustomItem)
End Class

任何关于我哪里出错的线索将不胜感激。还提示了如何深入 WPF 对象模型以查看运行时公开的属性,我也可以通过这种方式弄清楚。

问候

瑞安

最佳答案

您必须使用将代表您的类的内容的属性的名称来初始化 ContentPropertyAttribute。在您的情况下,因为您从 ObservableCollection 继承,这将是 Items 属性。不幸的是,Items 属性是只读的,这是不允许的,因为 Content 属性必须有一个 setter。因此,您必须围绕 Items 定义一个自定义包装器属性并在您的属性中使用它 - 如下所示:

public class MyCustomItem
{ }

[ContentProperty("MyItems")]
public class MyCustomCollection : ObservableCollection<MyCustomItem>
{
public IList<MyCustomItem> MyItems
{
get { return Items; }
set
{
foreach (MyCustomItem item in value)
{
Items.Add(item);
}
}
}
}

你应该没事的。很抱歉,当您的示例在 VB 中时,在 C# 中这样做,但我真的很讨厌 VB,甚至连这么简单的事情都做对了……无论如何,转换它很容易,所以 - 希望有所帮助。

关于wpf - 如何解决 WPF 设计器错误 'The type {0} does not support direct content' .'?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/356663/

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