-1

我有一个在 XAML 文件中定义的数据模板。XAML 的根不是资源字典,而是数据模板本身。现在我想将此数据模板添加到控件的资源中。不幸的是,我不知道使用什么键。

myControl.Resources.Add(???, dataTemplate);

虽然我使用数据模板 DataType 属性(即我想要模板的类型),但 WPF 资源查找引擎不使用我的数据模板。

任何人?谢谢!

编辑: 我知道使用样式,目标的类型可以解决问题,但是使用数据模板,这似乎有所不同......

编辑:

答:好的,我做了一点调试。这是正确的代码

myControl.Resources.Add(new DataTemplateKey(typeof(...)), dataTemplate);
4

2 回答 2

0

Actually Moser is right,

DataTemplates work on data objects.. ControlTemplates are for well.. controls... If your DataTemplate is for, lets say Car objects, use Mosers example like so:

myControl.Resources.Add(typeof(Car), dataTemplate);

Set your Car object on DataContext of the control that needs to use this DataTemplate, et voila :)


Or you could always make up your own key:

myControl.Resources.Add("MyAwesomeDataTemplate", dataTemplate);

And then set the Template property like so:

Template="{StaticResource MyAwesomeDataTemplate}"
于 2009-01-29T11:21:12.640 回答
0

使用为其设计数据模板的类型作为键:myControl.Resources.Add(typeof(TheType), dataTemplate);

于 2009-01-29T11:02:57.110 回答