How to get button content to fill width in WPF How to get button content to fill width in WPF wpf wpf

How to get button content to fill width in WPF


You should set Button.Template. Also Grid.ColumnDefinitions can be used to set the position and width of elements inside properly.

        <Button Height="30" Content="Smaple text">            <Button.Template>                <ControlTemplate TargetType="{x:Type Button}">                    <Grid>                        <Border Background="{TemplateBinding Background}"                         BorderBrush="{TemplateBinding BorderBrush}"                         BorderThickness="{TemplateBinding BorderThickness}">                            <Grid>                                <Grid.ColumnDefinitions>                                    <ColumnDefinition Width="Auto"/>                                    <ColumnDefinition Width="*"/>                                </Grid.ColumnDefinitions>                                <ContentPresenter HorizontalAlignment="Left"  Grid.Column="0"                                          VerticalAlignment="Center"/>                                <Canvas Background="AliceBlue" Grid.Column="1" />                            </Grid>                        </Border>                    </Grid>                </ControlTemplate>            </Button.Template>        </Button>


You could also set the HorizontalContentAlignment to Stretch on the Button itself.

This will tell the content to fill the horizontal space available on the button.

<Window    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"    x:Name="Window"    Title="test"    Width="640" Height="480">    <Grid x:Name="LayoutRoot">        <Button Height="30" HorizontalContentAlignment="Stretch">            <Grid HorizontalAlignment="Stretch">                <TextBlock Text="Sample Text" HorizontalAlignment="Stretch" TextAlignment="Left"></TextBlock>                <Canvas Width="40" Background="AliceBlue" HorizontalAlignment="Right"></Canvas>            </Grid>        </Button>    </Grid></Window>