在运行时定义WPF控件模板

6
我想在运行时定义一个控件模板,这是否可能?我注意到了ControlTemplate类上的VisualTree属性。我还注意到它使用FrameworkElementFactory类。然而,我似乎无法使其正常工作。
是否可以在运行时创建ControlTemplate?
2个回答

9

是的,您可以使用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;

-2
WPF控件类有一个“模板”属性,您可以在运行时设置一个。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接