【问题标题】:Creating a custom-shaped button with one rounded corner创建具有一个圆角的自定义形状按钮
【发布时间】:2013-07-08 16:55:03
【问题描述】:

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

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

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

【问题讨论】:

标签: c# wpf wpf-controls


【解决方案1】:

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

【讨论】:

  • 谢谢伙计!有用。但是,我想知道如何为此设置内容?当我为按钮设置内容时,它不显示。
  • 要显示内容,您应该插入 ContentPresenter
猜你喜欢
  • 1970-01-01
  • 2020-11-04
  • 1970-01-01
  • 2019-11-17
  • 1970-01-01
  • 1970-01-01
  • 2021-11-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多