wpf WPF中的自定义形状按钮

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17532063/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 09:10:32  来源:igfitidea点击:

Custom Shaped Button in WPF

c#wpfwpf-controlscustom-controls

提问by Prabash Darshana

I have a requirement of creating a button which takes the shapes as displayed in the picture:

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

enter image description here

在此处输入图片说明

Can anyone please help me? Thanks in advance!

谁能帮帮我吗?提前致谢!

回答by cbcol

You could use a ControlTemplate to achieve that:

您可以使用 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>

Than you apply it to the button:

比你把它应用到按钮上:

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

If you need some references to draw the "Path" check thisMSDN link.

如果您需要一些参考来绘制“路径”,请检查MSDN 链接。

Update

更新

To show the content you should use a ContentPresenter, something like this:

要显示您应该使用 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>

In the button:

在按钮中:

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

enter image description here

在此处输入图片说明