如何为集合创建DataTemplate?

问题描述:

我希望能够创建一个DataTemplate集合传递到控件时使用。如何为集合创建DataTemplate?

我正在构建一个控件,当传递一个对象或一组对象时,用户控件的视图符合为该对象类型定义的模板。

例如,这是我拥有的用户控件,它在对象传递到.Content属性时切换视图。

<UserControl x:Class="Russound.Windows.UI.UserControls.MAX.OMS_Main_Screen.OMSContextSwitcher" 
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
      xmlns:Entities="clr-namespace:Russound.Components.ReturnAuthorization.Entities;assembly=Russound.Components" 
      xmlns:Return_Authorization="clr-namespace:Russound.Windows.UI.UserControls.Return_Authorization" 
      xmlns:CallLog="clr-namespace:Russound.Windows.UI.UserControls.CallLog" 
      xmlns:Entities1="clr-namespace:Russound.Components.Membership.Entities;assembly=Russound.Components" 
      xmlns:Membership="clr-namespace:Russound.Windows.UI.UserControls.Membership" 
      xmlns:Entities2="clr-namespace:Russound.Components.Commerce.MAX.Entities;assembly=Russound.Components" 
      xmlns:OMS_Main_Screen="clr-namespace:Russound.Windows.UI.UserControls.MAX.OMS_Main_Screen" 
      xmlns:Entities3="clr-namespace:Russound.Components.CallLog.Entities;assembly=Russound.Components" 
      MinHeight="600" MinWidth="700"> 

    <UserControl.Resources> 
     <ResourceDictionary> 
      <ResourceDictionary.MergedDictionaries> 
       <ResourceDictionary Source="/Russound.Windows;component/UI/RussoundDictionary.xaml"/> 
      </ResourceDictionary.MergedDictionaries> 

       <DataTemplate DataType="{x:Type Entities3:Case}" > 
        <CallLog:CaseReadOnlyDisplay DataContext="{Binding}" /> 
       </DataTemplate> 

       <DataTemplate DataType="{x:Type Entities:RAMaster}"> 
        <Return_Authorization:RaMasterUi DataContext="{Binding}" /> 
       </DataTemplate> 

       <DataTemplate DataType="{x:Type Entities1:RussUser}"> 
        <Membership:CMCControlWpf DataContext="{Binding}" /> 
       </DataTemplate > 

       <DataTemplate DataType="{x:Type Entities2:MaxCustomer}"> 
        <OMS_Main_Screen:MaxCustomerConfigWpf DataContext="{Binding}" /> 
       </DataTemplate > 


     </ResourceDictionary> 
    </UserControl.Resources> 
</UserControl> 

我希望能够做这样的事情:

<DataTemplate DataType="{x:Type IEnumerable<MaxCustomer>}"> 
    <OMS_Main_Screen:MaxCustomerConfigWpf DataContext="{Binding}" /> 
</DataTemplate > 

,但我总是得到一个编译器错误,所以我在有点茫然的。

您可以创建一个类型集合,并直接

public class MyCollection:IEnumerable<MaxCustomer> 
{ 
    .... 
} 

<DataTemplate DataType="{x:Type Entities:MyCollection}"> 
      <OMS_Main_Screen:MaxCustomerConfigWpf DataContext="{Binding}" /> 
</DataTemplate > 
+2

+1使用该类型代替了IEnumerable的,你不能做OP想要的东西的原因是因为WPF不允许在接口模板。 – user7116 2009-12-21 18:58:46

+0

是的,那是我一直在倾斜。我只是想知道这里是否有另一种攻击方法。 – Russ 2009-12-21 19:35:24