How to create a datatemplate in code behind? RRS feed

  • Question

  • Hi,

    I have xaml 

    <Control1 x:Name="something">

    <DataTemplate> <Ellipse Width="35" Height="35" Fill="Red"> </Ellipse> </DataTemplate></Control1>

    Now I want to use pure C# code in code behind, how?

    Tuesday, November 14, 2017 12:18 AM

All replies

  • Hi,

    To create  templates in code behind, you can use FrameworkElementFactory class.

    But see the remarks :

    This class is a deprecated way to programmatically create templates, which are subclasses of FrameworkTemplate such as ControlTemplate or DataTemplate; not all of the template functionality is available when you create a template using this class. The 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.

    So you can try this.

    public DataTemplate Create()
        StringReader stringReader = new StringReader(
                <Ellipse Width="35" Height="35" Fill="Red">
        XmlReader xmlReader = XmlReader.Create(stringReader);
        return XamlReader.Load(xmlReader) as DataTemplate;

    Best Regards,


    MSDN Community Support
    Please remember to click "Mark as Answer" the responses that resolved your issue, and to click "Unmark as Answer" if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to MSDN Support, feel free to contact

    Tuesday, November 14, 2017 6:06 AM
  • I think Bob's made a good suggestion.

    Just to add...

    All the stuff you see in markup like


    Are classes.

    Meaning you could new one up in code.

    With anything but the simplest of cases, this can get pretty fiddly and is quite difficult to troubleshoot.

    If you instead create xaml as a string and xamlreader.parse or load it, then you can easily test it and troubleshoot bugs by just pasting into a window.

    If you wanted a number of templates to be created once and re-used you could write them to a flat uncompiled resource dictionary. You can merge one of these just like you can a compiled one.

    I wrote a bunch of samples which you might find interesting:

    Hope that helps.

    Technet articles: WPF: Layout Lab; All my Technet Articles

    Tuesday, November 14, 2017 9:05 AM