2009-04-09 60 views
5

我想在运行时定义一个ControlTemplate。这可能吗?我注意到了ControlTemplate类的VisualTree属性。我也注意到它使用了FrameworkElementFactory类。但是,我似乎无法让它工作。在运行时定义一个WPF ControlTemplate

是否可以在运行时创建ControlTemplate?

回答

8

是的,你可以使用FrameworkElementFactory来做到这一点。 Charles Petzold在“应用程序=代码+标记”第11章中对此进行了介绍,但其基本思想是为模板根元素(以及针对任何子元素的更多工厂)创建FrameworkElementFactory,创建ControlTemplate并设置将ControlTemplate的VisualTree属性添加到FrameworkElementFactory:

FrameworkElementFactory borderFactory = new FrameworkElementFactory(typeof(Border)); 
// set properties and create children of borderFactory 
ControlTemplate template = new ControlTemplate(); 
template.VisualTree = borderFactory; 

myButtonInstance.Template = template; 
-1

WPF控件类有一个'模板'属性,您可以在运行时设置它。