Search code examples
wpfxamlcontroltemplatewpf-style

Set size of border inside ControlTemplate to size of button


I want a ControlTemplate for a few buttons so I can control the colour of the button when the mouse is over it. The problem is that I use a border as the ControlTemplate content and I want the size (BorderThickness) of that border to be equal to the button's size. And since the button is part of a grid, its size is flexible. This is my code so far:

<Window x:Class="WPFTesting.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WPFTesting"
    mc:Ignorable="d"
    Title="MainWindow" Height="400" Width="350">

<Window.Resources>
    <Style TargetType="Button" x:Key="ex">
        <Setter Property="Background" Value="Black"/>
        <Setter Property="Foreground" Value="White"/>
        <Setter Property="FontSize" Value="50"/>
        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate>
                    <Border BorderBrush="{TemplateBinding Background}">
                        <ContentPresenter HorizontalAlignment="Center" VerticalAlignment="Center"/>
                    </Border>
                </ControlTemplate>
            </Setter.Value>
        </Setter>
    </Style>
</Window.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition/>
        <RowDefinition/>
        <RowDefinition/>
    </Grid.RowDefinitions>
    <Button Content="Btn0" Margin="0, 10, 0, 30" Style="{StaticResource ex}" Grid.Row="0"/>
    <Button Content="Btn1" Margin="0, 10, 0, 30" Grid.Row="1"/>
    <Button Content="Btn2" Margin="0, 10, 0, 30" Grid.Row="2"/> 
</Grid>
How can I make the BorderThickness fill the entire grid row. Should I even be using a border as the ControlTemplate content in the first place?

Solution

  • You should just write

    <ControlTemplate TargetType="Button">
        <Border Background="{TemplateBinding Background}"
                BorderBrush="{TemplateBinding BorderBrush}">
            <ContentPresenter
                HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}"
                VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
        </Border>
    </ControlTemplate>