创建一个带有一个圆角的自定义形状的按钮 [英] Creating a custom-shaped button with one rounded corner
问题描述
我需要在WPF中创建一个具有自定义形状的按钮。具体来说,我希望它具有圆角,如椭圆形。这是一张图片:
I need to create a button in WPF that has a custom shape. Specifically, I want it to have rounded corners, like an ellipse. Here is a picture:
只有黑色区域应该是点击目标;白色区域应该是透明的。
Only the black area should be a click target; the white area should be transparent.
我将如何在具有这种自定义形状的WPF中创建按钮控件?我知道如何创建一个常规的矩形按钮,但是没有一个这样的圆角按钮。
How would I go about creating a button control in WPF that has such a custom shape? I know how to create a regular rectangular button, but not one with a rounded corner like this.
推荐答案
您可以使用ControlTemplate要实现以下目的:
You could use a ControlTemplate to achieve that:
<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}"/>
如果需要一些参考来绘制路径,请选中此 MSDN链接。
If you need some references to draw the "Path" check this MSDN link.
更新
要显示内容,您应该使用ContentPresenter,如下所示:
To show the content you should use a ContentPresenter, something like this:
<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>
这篇关于创建一个带有一个圆角的自定义形状的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!