gpt4 book ai didi

wpf - 在 WPF 中以编程方式创建 ControlTemplate

转载 作者:行者123 更新时间:2023-12-04 19:22:21 25 4
gpt4 key购买 nike

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

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;

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

谢谢。

最佳答案

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

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

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

关于wpf - 在 WPF 中以编程方式创建 ControlTemplate,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2533510/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com