Officially, you should create XAML for the new ControlTemplate as a string, and then materialize it as a ControlTemplate object using XamlReader.Parse.
A more structured way to do this is to use the FrameworkElementFactory class - create a FrameworkElementFactory and set ControlTemplate.VisualTree for this FEF. This gives you improved type safety and avoids the awkwardness of writing a tree of objects in order to read it again. However, it is officially outdated and can become quite complex if you have a complex template.
See How do I customize a WPF data template in code for a tree image? for examples of both approaches - they are written in the context of a DataTemplate, but will work for a ControlTemplate as well.
source share