对于自定义DataTemplateSelector,我使用了ContentProperty属性,该属性应表示DataTemplates的集合。
\n\n[ContentProperty(nameof(Templates))]\npublic class CustomTemplateSelector : DataTemplateSelector\n{\n public List<DataTemplate> Templates { get; } = new List<DataTemplate>();\n\n public override DataTemplate SelectTemplate(object item, DependencyObject container)\n {\n /* \xe2\x80\xa6 */\n }\n}\nRun Code Online (Sandbox Code Playgroud)\n\nXAML中的用法:
\n\n<ItemsControl ItemsSource="{Binding MyCollection}">\n <ItemsControl.ItemTemplateSelector>\n <local:CustomTemplateSelector>\n <DataTemplate DataType="{x:Type system:Boolean}">\n <Label>BOOL</Label>\n </DataTemplate>\n <DataTemplate DataType="{x:Type system:String}">\n <Label>STRING</Label>\n </DataTemplate>\n </local:CustomTemplateSelector>\n </ItemsControl.ItemTemplateSelector>\n</ItemsControl>\nRun Code Online (Sandbox Code Playgroud)\n\n我的问题是为什么我不能使用IListorICollection数据类型而不是List数据类型。
如果我使用这些类型,则会收到编译错误Cannot set content property \'Templates\' on element \'CustomTemplateSelector\'。“模板”的访问级别不正确或其程序集不允许访问。
\n为了接受多个对象元素作为内容,XAML 内容属性的类型必须支持集合类型。
虽然这是相当模糊的,但似乎如果ContentProperty类型是集合,它必须实现非泛型IList接口,它List<T>确实实现了,但IList<T>没有实现。
所以
public IList Templates { get; } = new List<DataTemplate>();
Run Code Online (Sandbox Code Playgroud)
有效,但是
public IList<DataTemplate> Templates { get; } = new List<DataTemplate>();
Run Code Online (Sandbox Code Playgroud)
不会,因为IList<DataTemplate>不是IList.
| 归档时间: |
|
| 查看次数: |
1767 次 |
| 最近记录: |