我想在运行时定义一个控件模板,这是否可能?我注意到了ControlTemplate类上的VisualTree属性。我还注意到它使用FrameworkElementFactory类。然而,我似乎无法使其正常工作。
是否可以在运行时创建ControlTemplate?
是否可以在运行时创建ControlTemplate?
是的,您可以使用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;