2009-04-09 70 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控件類有一個'模板'屬性,您可以在運行時設置它。