0

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.

 <UserControl.Resources>
   <DataTemplate x:Key="myCellTemplate">
     <TextBlock Text="{Binding Description}" Margin="4"/>
   </DataTemplate>
 </UserControl.Resources>

Is there any way to define it in code-behind? Thank you.

Tyler Morrow
  • 949
  • 8
  • 31
Naseem
  • 41
  • 1
  • 5
  • possible duplicate of [Creating a Silverlight DataTemplate in code](http://stackoverflow.com/questions/59451/creating-a-silverlight-datatemplate-in-code) – Tyler Morrow Jul 29 '14 at 03:59

1 Answers1

1

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
  • 27,329
  • 4
  • 56
  • 102
  • 1
    Thank you . I'm working with Silverlight 3 and I couldn't find FrameworkElementFactory – Naseem May 05 '10 at 01:42
  • Thank you . In regards to your answer: http://stackoverflow.com/questions/59451/creating-a-silverlight-datatemplate-in-code – Naseem May 05 '10 at 03:24