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屬性,而不是在CodeBehind中創建整個Template。
你真正問的是如何在代碼中創建控件模板,因爲所有的風格確實是分配的模板。也許你應該改變你的問題的標題。 – 2012-07-22 00:38:11