DataType的DataTemplate - 如何在特定的ListBox中覆盖此DataTemplate?

时间:2010-11-02 10:43:25

标签: c# wpf datatemplate itemtemplate datatemplateselector

我为我的宠物项目中的一些DataType创建了几个DataTemplates。 这些数据模板非常酷,因为它们像魔术一样工作,无论何时何地在UI中显示,都可以神奇地转换数据类型实例的外观。 现在我希望能够在一个特定的ListBox中更改这些DataType的DataTemplate。这是否意味着我必须停止依赖WPF自动将数据模板应用于数据类型并将x:Key分配给DataTemplates,然后使用该键在UI中应用Template / ItemTemplate?

ListBox包含各种数据类型的项目(所有数据类型都来自公共基类),现在它们都可以在不指定TemplateSelector的情况下神奇地工作,因为正确的模板是由listBox中项目的实际数据类型选择的。如果我使用x:Key来应用DataTemplates,那么我是否需要编写TemplateSelector?

我是新手,只尝试使用DataTemplates。我想,哇,有多酷!然后我想在不同的列表框和ooops中为相同的数据类型使用不同的数据模板,我不能这样做:-)请帮助吗?

1 个答案:

答案 0 :(得分:3)

您可以专门为ItemTemplate

指定ListBox
<ListBox>
    <ListBox.ItemTemplate>
        <DataTemplate>
            <!-- your template here -->
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>

或者,如果您已经在DataTemplate某处定义了ResourceDictionary

<DataTemplate x:Key="MyTemplate">
      <!-- your template here -->
</DataTemplate>

然后您可以使用以下内容在ListBox上引用它

<ListBox ItemTemplate="{StaticResource MyTemplate}" />

您无需为这些方法中的任何一种编写模板选择器


示例以回应评论

下面的示例演示了如何为窗口定义数据类型的默认DataTemplate(在本例中为String),然后在列表框中覆盖它:

<Window x:Class="WpfApplication1.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:sys="clr-namespace:System;assembly=mscorlib"
        Title="MainWindow" Height="350" Width="525">
    <Window.Resources>
        <DataTemplate DataType="{x:Type sys:String}">
            <Rectangle Height="10" Width="10" Margin="3" Fill="Red" />
        </DataTemplate>
    </Window.Resources>
    <Grid>
        <ListBox>
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <Rectangle Height="10" Width="10" Margin="3" Fill="Blue" />
                </DataTemplate>
            </ListBox.ItemTemplate>

            <sys:String>One</sys:String>
            <sys:String>Two</sys:String>
            <sys:String>Three</sys:String>
        </ListBox>
    </Grid>
</Window>

这会产生以下UI:

Example Display