对于自定义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>
我的问题是为什么我不能使用 IList
或 ICollection
数据类型而不是 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/