wpf - WPF中的圆角扁平按钮

标签 wpf

我正在设计一个带有圆形平面按钮的WPF用户界面。我为这种按钮编写了以下代码:

<Border BorderThickness="1"
        BorderBrush="Transparent"
        Background="DarkCyan"
        CornerRadius="4"
        Height="35"
        Width="75">
            <Button Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"
                    Content="Enter"
                    VerticalAlignment="Stretch"
                    HorizontalAlignment="Stretch"
                    Background="DarkCyan"
                    Foreground="White"/>
</Border>

这个按钮的样式正是我所需要的。但是在运行时,当鼠标移至该按钮时,就不再舍入。它是一个具有相同大小的矩形。实际上,按钮溢出了边框。所以我像这样在边框上添加了padding:
<Border BorderThickness="1"
        BorderBrush="Transparent"
        Background="DarkCyan"
        CornerRadius="4"
        Height="35"
        Width="75"
        Padding="2">
            <Button Style="{StaticResource {x:Static ToolBar.ButtonStyleKey}}"
                    Content="Enter"
                    VerticalAlignment="Stretch"
                    HorizontalAlignment="Stretch"
                    Background="DarkCyan"
                    Foreground="White"/>
</Border>

在这种情况下,hoover mode中的按钮不再溢出边框,但是它仍然是矩形,因此按钮的颜色(在hoover mode中)在此矩形和其他边框空间中有所不同。因此,不幸的是它还没有用。

现在我的问题是:是否有任何方法可以构建一个圆角的平面按钮(如我提到的那样),使移动到该按钮上的标记空间恰好是圆角的空间?

最佳答案

这可能取决于按钮的VisualStateManager,当鼠标悬停在按钮上时,该样式会更改样式。我建议改用Style

<Style TargetType="Button" x:Key="FlatButtonStyle">
    <Setter Property="Background" Value="DarkCyan"/>
    <Setter Property="Foreground" Value="White"/>
    <Setter Property="Width" Value="75"/>
    <Setter Property="Height" Value="35"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="Button">
                <Border BorderThickness="0"
                        Background="{TemplateBinding Background}"
                        CornerRadius="4">
                     <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
               </Border>
           </ControlTemplate>
       </Setter.Value>
    </Setter>
</Style>

用法:
<Button Style="{StaticResource FlatButtonStyle}" ... />

关于wpf - WPF中的圆角扁平按钮,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30479746/

相关文章:

c# - DependencyProperty导致Visual Studio在设计时崩溃

c# - 在 WPF DataGrid 中格式化可为空的日期时间

wpf - 如何在VB.NET/WPF应用程序中拥有一个全局字典来保存来自不同窗口的数据?

c# - 如何调试具有异步数据访问且没有调用堆栈的 WPF 应用程序?

wpf - 无法更新 DataGrid

c# - 在 WPF 或 Silverlight 中单击透明图像

c# - 从业务层到UI的错误处理

c# - 按钮内的 WPF 按钮单击问题

c# - 所选文本未显示在 WPF 窗口中的 Windows 窗体 RichTextBox 控件中

c# - WPF - GridView.GridViewColumn 每行两行?