c# - WPF – 集合内容属性

标签 c# wpf xaml

对于自定义DataTemplateSelector,我使用了ContentProperty属性,该属性应表示DataTemplates的集合。

[ContentProperty(nameof(Templates))]
public class CustomTemplateSelector : DataTemplateSelector
{
    public List<DataTemplate> Templates { get; } = new List<DataTemplate>();

    public override DataTemplate SelectTemplate(object item, DependencyObject container)
    {
        /* … */
    }
}

XAML中的用法:

<ItemsControl ItemsSource="{Binding MyCollection}">
    <ItemsControl.ItemTemplateSelector>
        <local:CustomTemplateSelector>
            <DataTemplate DataType="{x:Type system:Boolean}">
                <Label>BOOL</Label>
            </DataTemplate>
            <DataTemplate DataType="{x:Type system:String}">
                <Label>STRING</Label>
            </DataTemplate>
        </local:CustomTemplateSelector>
    </ItemsControl.ItemTemplateSelector>
</ItemsControl>

我的问题是为什么我不能使用 IListICollection 数据类型而不是 List 数据类型。

如果我使用这些类型,则会收到编译错误无法在元素“CustomTemplateSelector”上设置内容属性"template"。 "template"的访问级别不正确或其程序集不允许访问。

最佳答案

ContentPropertyAttribute 文档说的是

In order to accept more than a single object element as content, the type of the XAML content property must be supportable as a collection type.

虽然这很模糊,但似乎如果ContentProperty type 是一个集合,它必须实现非泛型 IList接口(interface),其中List<T>确实如此,但是IList<T>没有。

所以

public IList Templates { get; } = new List<DataTemplate>();

有效,但是

public IList<DataTemplate> Templates { get; } = new List<DataTemplate>();

不会,因为IList<DataTemplate>不是IList .

关于c# - WPF – 集合内容属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51723146/

相关文章:

c# - 从 .CS 代码文件中提取方法名称

c# - 调用 FFMPEG 从 Flash 电影创建缩略图时出错

wpf - 如何在 WPF 中找到任意字形的精确大小?

c++ - 以编程方式更改图像源

c# - 如何在不更改主机文件的情况下阻止对特定站点的访问,直到重新启动?

c# - 在 VisualStateManager 中交换画笔

c# - 如何使用自定义 WPF 控件上的依赖属性处理计算值

c# - UserControl 的本地化属性

c# - 将 StackPanel 子项绑定(bind)到 ObservableCollection

c# - Json.NET 使用根名称序列化对象