-1

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!

JD136
  • 113
  • 9

1 Answers1

0

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>
Clemens
  • 123,504
  • 12
  • 155
  • 268
  • Gotcha, I see what you mean about losing all visualizations of its states. I also am realizing that I can add a style different than a template. I am guessing that in the link I referred to, that button was keeping most of its state visualizations? Is there a simpler way to stylize the button (maybe without a ControlTemplate) to have the rounded corners, without losing all the default behaviors/states it would have? – JD136 May 20 '22 at 23:58
  • My apologies, I see there (in the other post) that @Crandel answered what I'm going after, though his isn't the accepted answer for some reason. – JD136 May 21 '22 at 00:10
  • Please see the edited answer. – Clemens May 21 '22 at 07:07