我为我的宠物项目中的一些数据类型创建了几个数据模板。
这些数据模板非常酷,因为它们像魔法一样工作,无论何时何地出现在 UI 中,都会神奇地改变数据类型实例的外观。
现在我希望能够在一个特定的列表框中更改这些数据类型的数据模板。这是否意味着我必须停止依赖 WPF 自动将数据模板应用到数据类型,并将 x:Key 分配给 DataTemplates,然后使用该键在 UI 中应用 Template/ItemTemplate?
ListBox 包含各种 DataType 的项目(全部派生自公共基类),就像现在一样,无需指定 TemplateSelector 即可神奇地工作,因为正确的模板是由 listBox 中项目的实际数据类型选择的。如果我选择使用 x:Key 来应用 DataTemplates,我是否需要编写 TemplateSelector?
我对此很陌生,只尝试使用 DataTemplates。有那么一刻我想,哇,多酷啊!然后我想要在不同的列表框中为相同的数据类型使用不同的数据模板,哎呀,我做不到:-) 请帮忙?
您可以指定一个ItemTemplate
专门为您ListBox
:
<ListBox>
<ListBox.ItemTemplate>
<DataTemplate>
<!-- your template here -->
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
或者,如果您已经定义了您的DataTemplate
in a ResourceDictionary
某处:
<DataTemplate x:Key="MyTemplate">
<!-- your template here -->
</DataTemplate>
然后你可以参考它ListBox
using:
<ListBox ItemTemplate="{StaticResource MyTemplate}" />
您不需要为这两种方法中的任何一种工作编写模板选择器
Example回应评论
下面的示例演示了定义默认值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:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)