tags:

views:

177

answers:

1

Hi ,

I have defined the DataTemplate in the XAML, however I need to change it to be defined at run time , because its binding is dynamic.

Is there any way to define it in codebehind?

Thank you,

A: 

You might be able to accomplish what you need with a custom DataTemplateSelector and I'd recommend that approach, if possible. That said, it is possible to create a DataTemplate in code:

Type type = typeof(MyUserControl); //for example    
var template = new DataTemplate();
template.VisualTree = new FrameworkElementFactory(type);
return template;

In this context, type is the type of visual element you want to have as the root of your template. If necessary, you could add additional elements using the factory, but in the one case where I've used this, I simply created UserControl elements to represent the different templates I was dynamically creating.


My apologies, this apparently isn't supported in Silverlight. In Silverlight, you have to use XamlReader.

Dan Bryant
Thank you . I'm working with Silverlight 3 and I couldn't find FrameworkElementFactory
Naseem
Thank you . In regards to your answer: http://stackoverflow.com/questions/59451/creating-a-silverlight-datatemplate-in-code
Naseem