Creating a ControlTemplate programmatically in WPF

How can I programmatically set a button template?

Polygon buttonPolygon = new Polygon(); buttonPolygon.Points = buttonPointCollection; buttonPolygon.Stroke = Brushes.Yellow; buttonPolygon.StrokeThickness = 2; // create ControlTemplate based on polygon ControlTemplate template = new ControlTemplate(); template.Childeren.Add(buttonPolygon); // This does not work! What the right way? //create button based on controltemplate Button button = new Button(); button.Template = template; 

So, I need a way to set my polygon as a button template. Suggestions?

Thanks.

+4
source share
1 answer

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.

+4
source

Source: https://habr.com/ru/post/1305361/