Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Corner-rounded flat button in WPF

Tags:

wpf

I am designing a UI with WPF having a rounded flat button. I wrote following code for this kind of button:

<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 padding to the border like this:

<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 mode does 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.

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?

like image 721
parseh Avatar asked May 27 '15 10:05

parseh


1 Answers

This is probably down to the VisualStateManager for the button which is changing the style when the mouse is hovering over the button. I would suggest using a Style instead.

<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}" ... />
like image 121
Mike Eason Avatar answered Sep 20 '22 04:09

Mike Eason