Define a WPF ControlTemplate at runtime

♀尐吖头ヾ 提交于 2019-12-19 07:59:49

问题


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?


回答1:


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;



回答2:


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



来源:https://stackoverflow.com/questions/732736/define-a-wpf-controltemplate-at-runtime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!