How do I create a datatemplate with content programmatically?

Corpsekicker picture Corpsekicker · Dec 8, 2011 · Viewed 27k times · Source

I want to do the following at runtime in code:

<DataTemplate x:Key="lightGreenRectangle">
        <Rectangle Fill="LightGreen"/>
    </DataTemplate>

So far I've got:

public DataTemplate GetColouredRectangleInDataTemplate(Color colour)
{
    DataTemplate dataTemplate = new dataTemplate();

    return dataTemplate;
}

Help? I know this isn't the most elegant way of styling a control, but the component I want to specify a colour for has a property called "PointTemplate" of type DataTemplate.

Answer

FunnyItWorkedLastTime picture FunnyItWorkedLastTime · Dec 8, 2011

If for whatever reason you need to create a DataTemplate programmatically you would do:

XAML:

<Grid x:Name="myGrid">
    <ContentControl ContentTemplate="{DynamicResource lightGreenRectangle}" />
</Grid>

Somewhere in your code:

    public static DataTemplate CreateRectangleDataTemplate()
    {
        var rectangleFactory = new FrameworkElementFactory(typeof(Rectangle));
        rectangleFactory.SetValue(Shape.FillProperty, new SolidColorBrush(System.Windows.Media.Colors.LightGreen));

        return new DataTemplate
                   {
                       VisualTree = rectangleFactory,
                   };
    }

    public static void AddRectangleTemplateToResources(FrameworkElement element)
    {
        element.Resources.Add("lightGreenRectangle", CreateRectangleDataTemplate());
    }

Then you just need to add the DataTemplate to a ResourceDictionary so it can be used. For example, in the code behind:

    public MainWindow()
    {
        InitializeComponent();
        AddRectangleTemplateToResources(myGrid);
    }

Hope this helps!