【发布时间】:2009-01-03 09:30:21
【问题描述】:
我有一个ItemsControl,其ItemsSource 在运行时绑定到ObservableCollection<Component>。我已经为 Component 类型定义了一个数据模板,它工作正常。
现在Component 有一个ObservableCollection<Control>,我想在我的Component Datatemplate 中添加另一个ItemsControl 来呈现所有控件。 Control 这是我自己的自定义对象,与 wpf 控件无关。
有不同类型的控件,因此我尝试使用ItemTemplateSelector 为每种类型选择正确的模板。在下面的示例中,为了保持较小,我只展示了一个模板"RWString",我发现它使用MyControlTemplateSelector 中的FindResource 覆盖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 是 ObservableCollection<Control> 类型的组件的属性。另外,我尝试使用ItemsTemplateSelector 的原因是ObservableCollection<Control> 包含泛型类型的对象,如Control<int> Control<string> 等,所有这些都源自Control,显然你不能创建引用泛型类型的数据模板。
Update3:删除了更新 2,因为它不相关。我通过将StaticResource 更改为DynamicResource 使ItemTemplateSelector 工作。但我不知道为什么会这样......
【问题讨论】:
标签: c# wpf datatemplate itemscontrol