繁体   English   中英

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

[英]DataTemplate for a DataType - how to override this DataTemplate in a particular ListBox?

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

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

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

您可以专门为ListBox指定ItemTemplate

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

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

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

然后你可以使用以下方法在ListBox上引用它:

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

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


响应评论的示例

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

<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:

示例显示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM