Create DataTemplate in codebehind

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

Leave a Comment