2009-01-03 80 views
1

我有一个ItemsControl的ItemsSource在运行时绑定到一个ObservableCollection组件> ObservableCollection <。我已经定义了一个类型为Component的数据模板,它工作正常。WPF Datatemplating一个ItemsControl

现在组件有一个ObservableCollection <控制>,我想添加另一个ItemsControl在我的组件数据模板中呈现所有的控件。这里的控件是我自己的与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类型的Component的一个属性。此外我之所以使用ItemsTemplateSelector的原因是,ObservableCollection控制>包含通用类型的对象,如控制< INT>控制<字符串>等等所有派生自控制和显然你不能创建数据模型引用泛型类型。

更新3:删除更新2,因为它是无关的。通过将StaticResource更改为DynamicResource,我得到了ItemTemplateSelector。但我不知道为什么这个工程...

回答

1

我猜这不适用于StaticResource,因为资源位于ItemsControl中,可能还没有在加载时创建StaticResources时进行评估。

加载时的DynamicResources在加载时评估为表达式,然后在请求时评估为正确的值。

尝试移动ItemsControl外部的资源。

+0

谢谢你是这个问题。我在运行时创建的itemscontrol内创建它 – Sharun 2009-01-05 13:17:39

0

在你绑定嵌套ItemsControl的行,路径是否正确?它目前是“Contrls”,应该是“Controls”吗?

+0

它是有争议的。我需要改变这个名字,尽管......这很混乱。 – Sharun 2009-01-03 10:52:22