c# - 动态绑定(bind)到 DataTemplate

标签 c# xaml data-binding windows-8 windows-runtime

我有一个 ListBox 和多个 DataTemplate,位于单独的文件中。

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

Styles.xaml 文件中:

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

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

我想根据列表中对象的类型更改 ListBoxItemTemplate

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

最佳答案

在没有 TemplateSelector 的情况下执行此操作的方法是指定 DataType 属性,而不指定 x:Key。

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

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

但我更喜欢使用TemplateSelector

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

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

然后就可以得到模板了:

var dataTemplate = (DataTemplate) dict["ItemTemplate1"];

关于c# - 动态绑定(bind)到 DataTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12880896/

相关文章:

C# Access 数据库查询

wpf - 如何更新我的 Visual Studio 解决方案以使其使用 WPF 4.0?

wpf - 更改 ListBoxItem 样式

data-binding - 绑定(bind)到链接中的 href 属性

c# - 如何从主项目发送附件

c# - 通过向下转换参数自动重载和调用函数

c# - 如何在 visual studio WPF 中绑定(bind) "publish version"属性

c# - 具有 XAML 中定义的选项的数据绑定(bind) WPF ComboBox?

c# Action<T> 如何处理匿名方法

c# - 如何在 XAML WPF 中访问自定义控件的属性