Window.Resources WPF 中按钮的圆角

Round the corners of a button in Window.Resources WPF

我是 WPF 的新手。我已经熟悉 ControlTemplateContentPresenter 和其他一些作品,但我正在努力创建一个圆角按钮,如 Window.Resources 所定义(或可能是一个单独的样式文件) .

无论如何,当我将它添加到 <Button/> 标签时,我得到一个圆角按钮:

<Button.Resources>
    <Style TargetType="Border">
        <Setter Property="CornerRadius" Value="5"/>
    </Style>
</Button.Resources>

但是,当我尝试将其包含在 Window.Resources 中时,该按钮不会应用边框样式:

<ControlTemplate x:Key="roundbutton" TargetType="Button">
    <Grid>
        <Rectangle Fill="{TemplateBinding Background}" Stroke="{TemplateBinding Foreground}"/>
        <Border CornerRadius="5"/>
        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
    </Grid>
</ControlTemplate>

我觉得这不对,但我想我不知道在哪里添加 CornerRadius 的规范,以便它适用于按钮。我确实看到了这个 post、How to create/make rounded corner buttons in WPF?,但有点难以理解。我只想将我应用程序中的所有按钮都四舍五入!

您的 ControlTemplate 中的边框不可见,因为您既没有设置它的背景,也没有设置它的 BorderBrush。

您可能会得到如下所示的内容。但是请注意,使用像这样的简单 ControlTemplate,Button 会丢失其状态的所有可视化,例如 focusedmouse-over按下

<ControlTemplate x:Key="roundbutton" TargetType="Button">
    <Border Background="{TemplateBinding Background}"
            BorderBrush="{TemplateBinding BorderBrush}"
            CornerRadius="5">
        <ContentPresenter/>
    </Border>
</ControlTemplate>

您可以声明一个默认的按钮样式(即没有 x:Key 的样式资源),它应用您的原始边框样式,如下所示:

<Style TargetType="Button">
    <Style.Resources>
        <Style TargetType="Border">
            <Setter Property="CornerRadius" Value="5"/>
        </Style>
    </Style.Resources>
</Style>