1

我需要使用 c# 代码创建这种样式来为多边形生成动态点,而不是在 xaml 标记中生成静态点。

 <Style  x:Key="Mystyle" TargetType="Button">
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid  >

                            <Polygon  Points="0,0 0,100 50,200" Fill="{TemplateBinding Background}"
                         Stroke="{TemplateBinding BorderBrush}" DataContext="{Binding}" />
                        <ContentPresenter HorizontalAlignment="Center"
                                      VerticalAlignment="Center"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
4

2 回答 2

4
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 中创建整个模板。

于 2012-07-22T06:44:49.913 回答
0

property in your class and bind your points dependency property with that property如果您不希望在 xaml 中预定义点,我建议您不要在代码中创建样式,而是使用。这就是Binding派上用场的地方。

于 2012-07-22T05:44:18.583 回答