我有一个ItemsControlwho在运行时ItemsSource绑定到一个。ObservableCollection<Component>我已经为类型定义了一个可以正常工作的数据模板Component。
现在Component有一个ObservableCollection<Control>,我想ItemsControl在我的内部添加另一个Component Datatemplate来呈现所有控件。Control这是我自己的与 wpf 控件无关的自定义对象。
有不同类型的控件,因此我尝试使用ItemTemplateSelector为每种类型选择正确的模板。在下面的示例中,为了保持较小,我只显示了一个"RWString"使用FindResourceinMyControlTemplateSelector覆盖的模板SelectTemplate。但是SelectTemplate永远不会被调用(使用断点检查)。我的 xaml 有问题吗?
<ItemsControl.Resources>
<src:MyControlTemplateSelector x:Key="XSelector" />
<DataTemplate DataType="{x:Type src:Component}" >
<Expander Visibility="{Binding Path=Show}">
<ItemsControl ItemsSource="{Binding Path=Contrls}"
ItemTemplateSelector="{StaticResource XSelector}">
<ItemsControl.Resources>
<DataTemplate x:Key="RWstring" >
<TextBlock Text="{Binding Path=Label}"/>
</DataTemplate>
</ItemsControl.Resources>
<ItemsControl.ItemsPanel>
<ItemsPanelTemplate><WrapPanel /></ItemsPanelTemplate>
</ItemsControl.ItemsPanel>
</ItemsControl>
</Expander>
</DataTemplate>
</ItemsControl.Resources>
更新: Contrls不是错字,只是我使用了一个愚蠢的命名系统。Contrls是 Component 类型的属性ObservableCollection<Control>。另外,我尝试使用 the 的原因ItemsTemplateSelector是ObservableCollection<Control> 包含泛型类型的对象,例如Control<int> Control<string>etc 都派生自Control,显然您无法创建引用泛型类型的数据模板。
更新 3 :删除更新 2,因为它不相关。我ItemTemplateSelector通过更改StaticResource为DynamicResource. 但我不知道为什么会这样......