WPF: Padding does not work on styled button

This is one of those things that can easily fall through the cracks when creating a new ControlTemplate for a WPF Button.

The problem

Let’s suppose you have the following code to render an OK and a Cancel button on the bottom of a window:

<Button Content="_OK" Margin="0,0,8,0" Padding="8,2"
        HorizontalAlignment="Center" VerticalAlignment="Center" />
<Button Content="_Cancel" Padding="8,2"
        HorizontalAlignment="Center" VerticalAlignment="Center" />

 

A nice padding was added to add some space between the content text and the outer borders of the button. This is how these buttons look:
Now you want to add a new ControlTemplate to your Button style and create a ContentPresenter within that template to accommodate the content the user of your style will provide, similar to what is achieved in this reference page at MSDN:
(…)
<ControlTemplate TargetType="Button">
    <Border x:Name="Border"
            CornerRadius="2" BorderThickness="1"
            Background="{StaticResource NormalBrush}"
            BorderBrush="{StaticResource NormalBorderBrush}">
        <ContentPresenter Margin="2"
                          HorizontalAlignment="Center"
                          VerticalAlignment="Center"
                          RecognizesAccessKey="True"/>
(…)
After applying this new style and running your application the subsequent picture shows how the buttons would look.
WpfTips0005

As you can see the nice space we had specified for our buttons with Padding is not visible anymore and the text almost touches the borders of our buttons. Basically the padding you are adding on your Button’s xaml is being ignored by the new style.

 

The solution

The solution to this problem is a very simple one. You just have to ensure that you bind your ContentPresenter’s margin to the TemplatedParent Padding property, as follows:

(…)
<ControlTemplate TargetType="Button">
    <Border x:Name="Border"
            CornerRadius="2" BorderThickness="1"
            Background="{StaticResource NormalBrush}"
            BorderBrush="{StaticResource NormalBorderBrush}">
        <ContentPresenter Margin="{TemplateBinding Padding}"
                          HorizontalAlignment="Center"
                          VerticalAlignment="Center"
                          RecognizesAccessKey="True"/>
(…)

This way a Padding will be applied when the Button’s content gets rendered. After this change this is how our would buttons look:

WpfTips0006

As you can see padding is now accounted for and our Buttons look much cooler!

Shout it kick it on DotNetKicks.com

One thought on “WPF: Padding does not work on styled button

  1. Pingback: DotNetShoutout

Leave a Reply

Your email address will not be published. Required fields are marked *