WPF中的自定义形状按钮

时间:2013-07-08 16:55:04

标签: c# wpf wpf-controls custom-controls

我需要创建一个按钮,该按钮采用图片中显示的形状:

enter image description here

任何人都可以帮助我吗? 提前谢谢!

1 个答案:

答案 0 :(得分:20)

您可以使用ControlTemplate来实现:

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="Black"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Path Fill="{TemplateBinding Background}"
                            Data="M 0,0 A 100,100 90 0 0 100,100 L 100,100 100,0" />
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

比将其应用于按钮:

<Button Style="{StaticResource ButtonStyle}"/>

如果您需要一些引用来绘制“路径”,请选中this MSDN链接。

<强>更新

要显示内容,您应该使用ContentPresenter,如下所示:

<Style x:Key="ButtonStyle" TargetType="{x:Type Button}">
        <Setter Property="Background" Value="Black"/>
        <Setter Property="HorizontalAlignment" Value="Center"/>
        <Setter Property="VerticalContentAlignment" Value="Center"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="{x:Type Button}">
                    <Grid>
                        <Path Fill="{TemplateBinding Background}"
                            Data="M 0,0 A 100,100 90 0 0 100,100 L 100,100 100,0" />
                        <ContentPresenter VerticalAlignment="{TemplateBinding VerticalContentAlignment}"
                                          HorizontalAlignment="{TemplateBinding HorizontalAlignment}"/>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>

在按钮中:

<Button Style="{StaticResource ButtonStyle}" Foreground="White">
        test
    </Button>

enter image description here