views:

297

answers:

2

Howdy,

I have a data template that is defined in a XAML file. The root of the XAML is not a resource dictionary but the data template itself. Now I want to add this data template to the resources of a control. Unfortunately, I don't know what key to use.

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

Although I use the data templates DataType property (i.e. the type that I want to template) the WPF resource lookup engine does not use my data template.

Anyone? Thanks!

EDIT: I know that with styles the type of the target would do the trick but with data templates this seems to be different...

EDIT:

Answer: Ok, I did a little bit of debugging. Here is the correct code

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

use as key the type for which the datatemplate is designed like: myControl.Resources.Add(typeof(TheType), dataTemplate);

Martin Moser
A: 

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}"
Arcturus