I would like to define a ControlTemplate at runtime. Is this possible? I have noticed the VisualTree property on the ControlTemplate class. I have also noticed that it uses the FrameworkElementFactory class. However, I cannot seem to get it to work.
Is it possible to create a ControlTemplate at runtime?
Yes, you can do this using FrameworkElementFactory. Charles Petzold has a walkthrough of this in chapter 11 of "Applications = Code + Markup," but the basic idea is that you create a FrameworkElementFactory for the template root element (and further factories for any child elements), create a ControlTemplate, and set the VisualTree property of the ControlTemplate to the FrameworkElementFactory:
FrameworkElementFactory borderFactory = new FrameworkElementFactory(typeof(Border));
// set properties and create children of borderFactory
ControlTemplate template = new ControlTemplate();
template.VisualTree = borderFactory;
myButtonInstance.Template = template;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With