Create ControlTemplate programmatically in WPF

17,406

Officially, you should create the XAML for the new ControlTemplate as a string, then materialise it as a ControlTemplate object using XamlReader.Parse.

A more structured way to do this is using the FrameworkElementFactory class -- create a FrameworkElementFactory and set ControlTemplate.VisualTree to that FEF. This gives you improved type safety and avoids the clunkiness of writing out an object tree just to read it in again. However, it is officially deprecated and can get rather complicated if you have a complicated template.

See How to setup a WPF datatemplate in code for a treeview? for examples of both approaches -- they are written in the context of a DataTemplate but will work for a ControlTemplate as well.

Share:
17,406
Thomas Stock
Author by

Thomas Stock

I'm a .NET developer that focuses on web technologies and UI. I love working with JavaScript and I believe that this language will play a major role in future software development. My weapons of choice are: ASP.NET MVC (+ Web API) jQuery / AngularJS Umbraco CMS Xamarin (iOS Development) I also have a strong interest in: UX design / Usability Rock Climbing I'm not afraid of css and I think twitter is overrated :-) Specialties: Front-end, JavaScript, .NET

Updated on June 04, 2022

Comments

  • Thomas Stock
    Thomas Stock almost 2 years

    How can I programmatically set a button's 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's 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 the button's template. Suggestions?

    Thanks.