New to Telerik UI for WPF? Download free 30-day trial

Using DataTemplate in Code

This article shows how to get or create a DataTemplate in code using few different approaches.

Defining the Template in XAML

The most conveninent approach is to define the DataTemplate in XAML and get it in code when needed.

Example 1: Defining the DataTemplate in XAML

    <DataTemplate x:Key="MyDataTemplate"> 
        <TextBlock Text="{Binding MyProperty}" /> 

Example 2: Getting the DataTemplate in code

public partial class MyUserControl : UserControl 
    public MyUserControl() 
        DataTemplate template = (DataTemplate)this.Resources["MyDataTemplate"]; 

Defining the Template in Code as a String

If you don't have access to XAML you can define the DataTemplate as a string and use the XamlReader.Parse static method to parse the string to a DataTemplate object.

When using this approach you need to add all the namespaces required by the elements in the DataTemplate manually in the string or the parser context.

Example 3: Parsing a string containing a DataTemplate

var dataTemplateString =  
    @"<DataTemplate>" + 
        @"<StackPanel>" + 
            @"<telerik:RadButton Content=""Button Content"" />" + 
            @"<TextBlock Text=""{Binding }"" />" + 
            @"<local:MyCustomControl />" + 
        @"</StackPanel>" + 
ParserContext parserContext = new ParserContext(); 
// This namespace is required for all the default elements that don't require a prefix, like DataTemplate, TextBlock, StackPanel, etc. 
parserContext.XmlnsDictionary.Add("", ""); 
// This is the telerik namespace required by the RadButton in this case. 
parserContext.XmlnsDictionary.Add("telerik", ""); 
// This is a local namespace pointing to a namespace from your application. The same approach is used for any other namespaces. 
parserContext.XmlnsDictionary.Add("local", "clr-namespace:MyNamespace;assembly=MyAssemblyName"); 
DataTemplate template = (DataTemplate)XamlReader.Parse(dataTemplateString, parserContext); 

Using FrameworkElementFactory

Creating a DataTemplate in code is not as simple as creating a visual element, like аn heir of UIelement for example. To do so you will need to use the FrameworkElementFactory class. As this is the least recommended approach for creating a DataTemplate in code there won't be example for it. But, if you need to use it check the FrameworkElementFactory documentation in MSDN.

See Also

In this article