在WPF中以编程方式创建ControlTemplate [英] Create ControlTemplate programmatically in WPF

查看:102
本文介绍了在WPF中以编程方式创建ControlTemplate的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何以编程方式设置按钮的模板?

How can I programmatically set a button's template?

Polygon buttonPolygon = new Polygon();
buttonPolygon.Points = buttonPointCollection;
buttonPolygon.Stroke = Brushes.Yellow;
buttonPolygon.StrokeThickness = 2;

// create ControlTemplate based on polygon
ControlTemplate template = new ControlTemplate();
template.Childeren.Add(buttonPolygon); // This does not work! What's the right way?

//create button based on controltemplate
Button button = new Button();
button.Template = template;

因此,我需要一种将多边形"设置为按钮模板的方法.有建议吗?

So I need a way to set my Polygon as the button's template. Suggestions?

谢谢.

推荐答案

正式地,您应该为新ControlTemplate作为字符串创建XAML,然后使用XamlReader.Parse将其具体化为ControlTemplate对象.

Officially, you should create the XAML for the new ControlTemplate as a string, then materialise it as a ControlTemplate object using XamlReader.Parse.

一种更结构化的方法是使用FrameworkElementFactory类-创建一个FrameworkElementFactory并将ControlTemplate.VisualTree设置为该FEF.这为您提供了改进的类型安全性,并避免了为再次读取而写出对象树的笨拙.但是,正式弃用了该模板,如果您使用的模板很复杂,则会变得相当复杂.

A more structured way to do this is using the FrameworkElementFactory class -- create a FrameworkElementFactory and set ControlTemplate.VisualTree to that FEF. This gives you improved type safety and avoids the clunkiness of writing out an object tree just to read it in again. However, it is officially deprecated and can get rather complicated if you have a complicated template.

请参阅如何设置WPF数据模板是这两种方法的示例吗?它们是在DataTemplate的上下文中编写的,但也适用于ControlTemplate.

See How to setup a WPF datatemplate in code for a treeview? for examples of both approaches -- they are written in the context of a DataTemplate but will work for a ControlTemplate as well.

这篇关于在WPF中以编程方式创建ControlTemplate的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆