如何为集合创建DataTemplate?

时间:2009-12-21 18:30:39

标签: wpf data-binding .net-3.5 collections 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 >

但是我总是遇到编译错误,所以我有点不知所措。

1 个答案:

答案 0 :(得分:3)

您可以创建一个类型化集合并直接使用该类型而不是IEnumerable

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

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