Create DataTemplate in code behind

MYRAO picture MYRAO · Mar 29, 2011 · Viewed 30.3k times · Source

How do i add controls to datatemplates programmatically?

For Example. Below I've created TextBlock and DataTemplate.

TextBlock text = new TextBlock();
DataTemplate template = new DataTemplate();

Now I need to add TextBlock to DataTemplate. How to achieve this?

I know that there are other ways of addind data template in code behind 1. create a data template in XAML and load it on code behind 2. create and add using XamlParser

but i need to do in the way i showed in example.

Need some help.

Answer

Russell Giddings picture Russell Giddings · Jun 14, 2013

Although Archedius's method works, officially it is deprecated and instead recommended way to programmatically create a template is to load XAML from a string or a memory stream using the Load method of the XamlReader class like this...

public DataTemplate Create(Type type)
{
    StringReader stringReader = new StringReader(
    @"<DataTemplate 
        xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""> 
            <" + type.Name + @" Text=""{Binding " + ShowColumn + @"}""/> 
        </DataTemplate>");
    XmlReader xmlReader = XmlReader.Create(stringReader);
    return XamlReader.Load(xmlReader) as DataTemplate;
}

Official line taken from msdn: http://msdn.microsoft.com/en-us/library/system.windows.frameworkelementfactory.aspx

Code example from Fredrik Hedblad's post here: Problems with XamlReader generating DataTemplate