gpt4 book ai didi

c# - 创建一个带有圆角的自定义形状按钮

转载 作者:太空狗 更新时间:2023-10-29 19:52:27 24 4
gpt4 key购买 nike

我需要在 WPF 中创建一个具有自定义形状的按钮。具体来说,我希望它有圆角,就像椭圆一样。这是一张图片:

只有黑色区域应该是点击目标;白色区域应该是透明的。

我将如何在 WPF 中创建具有这种自定义形状的按钮控件?我知道如何创建一个常规的矩形按钮,但不知道如何创建像这样的圆角按钮。

最佳答案

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

关于c# - 创建一个带有圆角的自定义形状按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17532063/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com