在WPF中以编程方式创建ControlTemplate

时间:2010-03-28 15:58:32

标签: wpf code-behind controltemplate

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

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;

所以我需要一种方法将我的Polygon设置为按钮的模板。建议?

感谢。

1 个答案:

答案 0 :(得分:5)

正式地说,您应该将新ControlTemplate的XAML创建为字符串,然后使用XamlReader.Parse将其实现为ControlTemplate对象。

更有条理的方法是使用FrameworkElementFactory类 - 创建FrameworkElementFactory并将ControlTemplate.VisualTree设置为该FEF。这样可以提高类型的安全性,并避免写出对象树的笨拙,只是为了再次读取它。但是,如果你有一个复杂的模板,它会被正式弃用,并且会变得相当复杂。

有关这两种方法的示例,请参阅How to setup a WPF datatemplate in code for a treeview? - 它们是在DataTemplate的上下文中编写的,但也适用于ControlTemplate。