【问题标题】:Create ControlTemplate programmatically in WPF在 WPF 中以编程方式创建 ControlTemplate
【发布时间】:2011-02-01 18:35:09
【问题描述】:

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

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;

所以我需要一种方法来将我的多边形设置为按钮的模板。有什么建议吗?

谢谢。

【问题讨论】:

    标签: wpf code-behind controltemplate


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-11
      • 1970-01-01
      • 2012-12-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多