Define WPF ControlTemplate at Run Time

I would like to define a ControlTemplate at runtime. Is it possible? I noticed a VisualTree property in the ControlTemplate class. I also noticed that it uses the FrameworkElementFactory class. However, I cannot get it to work.

Is it possible to create a ControlTemplate at run time?

+5
source share
2 answers

Yes, you can do this with FrameworkElementFactory. Charles Petzold has a walkthrough in Chapter 11, Applications = Code + Markup, but the main idea is that you create a FrameworkElementFactory for the root element of the template (and other factories for any child elements), create a ControlTemplate, and set the VisualTree property of the ControlTemplate to FrameworkElementFactory:

FrameworkElementFactory borderFactory = new FrameworkElementFactory(typeof(Border));
// set properties and create children of borderFactory
ControlTemplate template = new ControlTemplate();
template.VisualTree = borderFactory;

myButtonInstance.Template = template;
+8
source

The WPF Control class has a "Template" property that you can set at runtime.

-1
source

All Articles