Define a WPF ControlTemplate at runtime

前端 未结 2 345
时光取名叫无心
时光取名叫无心 2021-01-13 05:26

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

相关标签:
2条回答
  • 2021-01-13 05:54

    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;
    
    0 讨论(0)
  • 2021-01-13 06:07

    WPF Control class has a 'Template' property to which you can set a at run time.

    0 讨论(0)
提交回复
热议问题