问题描述
我想在运行时定义ControlTemplate.这可能吗?我注意到ControlTemplate类的VisualTree属性.我还注意到它使用FrameworkElementFactory类.但是,我似乎无法使其正常工作.
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.
是否可以在运行时创建ControlTemplate?
Is it possible to create a ControlTemplate at runtime?
推荐答案
是的,您可以使用FrameworkElementFactory进行此操作. Charles Petzold在应用程序=代码+标记"的第11章中对此进行了演练,但是基本思想是,为模板根元素(以及其他子元素的其他工厂)创建一个FrameworkElementFactory,创建一个ControlTemplate并设置ControlTemplate的VisualTree属性分配给FrameworkElementFactory:
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;
这篇关于在运行时定义WPF ControlTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!