public MainWindow()
{
//Control Template .. We cannot add children to the Control Template Directly
ControlTemplate controlTemplate = new ControlTemplate(typeof(Button));
//These points you can set Dynamically as your requirement
PointCollection points= new PointCollection(new List<Point> { new Point() { X = 0, Y = 0 }, new Point() { X = 0, Y = 50 }, new Point() { X = 100, Y = 200 } });
var polygon = new FrameworkElementFactory(typeof(Polygon));
//You can also set Binding rather than static color for fill
polygon.SetValue(Polygon.PointsProperty, points);
polygon.SetValue(Polygon.FillProperty, new SolidColorBrush(Colors.Pink));
//ContentPresenter
var contentPresenter = new FrameworkElementFactory(typeof(ContentPresenter));
contentPresenter.SetValue(ContentPresenter.ContentProperty,"this is content Presenter");
//Grid
var grid = new FrameworkElementFactory(typeof(Grid));
grid.SetValue(Grid.BackgroundProperty, new SolidColorBrush(Colors.Yellow));
grid.AppendChild(polygon);
grid.AppendChild(contentPresenter);
controlTemplate.VisualTree = grid;
//Style
Style style = new Style(typeof(Button));
style.Setters.Add(new Setter(BackgroundProperty, new SolidColorBrush(Colors.Red)));
style.Setters.Add(new Setter(TemplateProperty, controlTemplate));
this.Resources.Add("SomeKey", style);
//Initialize
InitializeComponent();
}
<Grid>
<Button Style="{DynamicResource SomeKey}"/>
</Grid>
我希望这将帮助您给出如何做的想法。是的,您可以在后面的代码中设置所有绑定,例如多边形的填充和 ContentPresenter 的内容。
注意 建议使用 Xaml 创建模板。在您的问题中,您想要的只是 Polygon 的动态 Points 。最好绑定 Polygon 的 Points 属性,而不是在 CodeBehind 中创建整个模板。