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" />
(…)
<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.
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:
As you can see padding is now accounted for and our Buttons look much cooler!
Trackbacks & Pingbacks