wpf WPF中的圆角扁平按钮
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30479746/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Corner-rounded flat button in WPF
提问by parseh
I am designing a UI with WPF having a rounded flat button. I wrote following code for this kind of button:
我正在设计一个带有圆形平面按钮的 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>
This button's style is exactly what I need. But at runtime, when the mouse moves to the button, it is not rounded anymore. It is a rectangle with same size. In fact, the button overflows the border. So I added paddingto the border like this:
这个按钮的样式正是我需要的。但是在运行时,当鼠标移动到按钮时,它不再是圆形的。它是一个大小相同的矩形。实际上,按钮溢出了边框。所以我添加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>
In this case, button in hoover modedoes not overflow the border anymore, But it is still rectangle and so button’s color (In hoover mode) differs in this rectangle and other spaces of border. So unluckily it is not useful yet.
在这种情况下,按钮 inhoover mode不再溢出边框,但它仍然是矩形,因此按钮的颜色 (In hoover mode) 在此矩形和边框的其他空间中不同。所以不幸的是它还没有用。
Now my question is: Is there any way to build a corner-rounded flat button (like the one I mentioned) that marked space in moving onto the button would be exactly the corner rounded space?
现在我的问题是:有没有办法建立一个圆角平面按钮(就像我提到的那个),移动到按钮上的标记空间就是圆角空间?
回答by Mike Eason
This is probably down to the VisualStateManagerfor the button which is changing the style when the mouse is hovering over the button. I would suggest using a Styleinstead.
这可能归结为VisualStateManager当鼠标悬停在按钮上时更改样式的按钮。我建议使用 aStyle代替。
<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>
Usage:
用法:
<Button Style="{StaticResource FlatButtonStyle}" ... />

