Home > Back-end >  Round the corners of a button in Window.Resources WPF
Round the corners of a button in Window.Resources WPF

Time:05-24

I am very new to WPF. I've familiarized myself with ControlTemplate, ContentPresenter, and some other pieces, but I am struggling to create a button with rounded corners as defined from Window.Resources (or potentially a separate style file).

Anyways, when I add this to a <Button/> tag, I get a button with rounded corners:

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

However, when I try to include it up in the Window.Resources the button will not apply the border style:

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

This doesn't look right to me, but I guess I don't know where to add the specification of CornerRadius such that it will apply to the button. I did see this post, How to create/make rounded corner buttons in WPF? but it's a little over my head. I just want to round all the buttons in my application!

CodePudding user response:

The Border in your ControlTemplate is not visible, because you have neither set its Background, nor its BorderBrush.

You could have something like shown below. Note however that with a simple ControlTemplate like this a Button loses all the visualizations of its states, like focused, mouse-over, pressed etc.

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

You may instead just declare a default Button Style (i.e. a Style resource without x:Key) that applies your original Border Style like this:

<Style TargetType="Button">
    <Style.Resources>
        <Style TargetType="Border">
            <Setter Property="CornerRadius" Value="5"/>
        </Style>
    </Style.Resources>
</Style>
  •  Tags:  
  • wpf
  • Related