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

标签 wpf designer contentproperty

以下 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/

相关文章:

c# - MVVM-有没有一种方法可以在不使用数据绑定(bind)的情况下获取和设置文本框的文本?

.net - WPF 仅在 Debug模式下显示控件

WPF如何强制设计器显示自定义窗口样式

visual-studio - 在 Xamarin 项目中可视化编辑 XAML 文件。 Visual Studio 2012

c# - 使用 x :Static 向 xaml 中的数组添加值

c# - 在 WPF 窗口及其用户控件之间共享数据的最佳方式是什么?

c# - WPF 为描边和填充塑造不同的不透明度

c++ - 以编程方式使 QToolButton 与 Qt Designer 中的相同

css - 如何使用 Google Material Icon 设置 CSS 内容属性?

c# - 如何覆盖/修改 Frame 的 Content 属性以接受 Xamarin.Forms 中的多个 View ?