在运行时定义WPF ControlTemplate

use*_*192 5 wpf controltemplate

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

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

ito*_*son 8

是的,您可以使用FrameworkElementFactory执行此操作.Charles Petzold在"Applications = Code + Markup"的第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;
Run Code Online (Sandbox Code Playgroud)