Tho*_*ock 5 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;
Run Code Online (Sandbox Code Playgroud)
所以我需要一种方法将我的Polygon设置为按钮的模板.建议?
谢谢.
正式地,您应该将新ControlTemplate的XAML创建为字符串,然后使用XamlReader.Parse将其实现为ControlTemplate对象.
更有条理的方法是使用FrameworkElementFactory类 - 创建FrameworkElementFactory并将ControlTemplate.VisualTree设置为该FEF.这样可以提高类型的安全性,并避免写出对象树的笨拙,只是为了再次读取它.但是,它已被正式弃用,如果您有一个复杂的模板,可能会变得相当复杂.
请参阅如何在树视图的代码中设置WPF datatemplate?两种方法的示例 - 它们都是在DataTemplate的上下文中编写的,但也适用于ControlTemplate.