2

我有一个ListBox和多个DataTemplates,在单独的文件中。

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

Styles.xaml文件中:

<DataTemplate x:Key="ItemTemplate1">...</DataTemplate>

<DataTemplate x:Key="ItemTemplate2">...</DataTemplate>

我想根据其列表中的对象类型ItemTemplate更改。ListBox

有没有办法访问DataTemplate代码隐藏中的单独 s,以便我可以绑定到 my 的属性Page

4

3 回答 3

1

试试这个解决方案几乎可以实现您想要实现的目标:

在 WP7 中按类型动态应用数据模板

http://www.codeproject.com/Articles/113152/Applying-Data-Templates-Dynamically-by-Type-in​​-WP7

它基于 WP7,但也适用于您。

于 2012-10-14T09:35:06.097 回答
1

做到这一点的方法TemplateSelector是指定 DataType 属性而不指定 x:Key。

<DataTemplate DataType="{x:Type Type1}">...</DataTemplate>
<DataTemplate DataType="{x:Type Type2}">...</DataTemplate>

在这种情况下,适当的 DataTemplate 将自动应用于已绑定指定类型属性的所有位置。

但我更喜欢使用TemplateSelector.

要在代码隐藏中访问分离的 DataTemplate,您应该首先获取资源字典:

var dict = new ResourceDictionary 
{Source = new Uri("/ProjectNamespace;component/Styles.xaml",  UriKind.Relative)};

然后你可以得到模板:

var dataTemplate = (DataTemplate) dict["ItemTemplate1"];
于 2012-10-14T10:28:53.290 回答
0

WPF 中有内置支持以满足您的要求。开始阅读DataTemplateSelector以在运行时根据特定条件选择模板。

于 2012-10-14T09:41:38.817 回答