Search code examples
wpfbuttonuser-controlswpf-controlsstackpanel

Stretching of WPF StackPanel


I'm playing around with WPF and I'm trying to create an ImageButton control. I've created a UserControl as follows:

<UserControl
         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" 
         mc:Ignorable="d" 
         x:Class="WpfPractise.Controls.ImageButton"
         Height="auto" Width="auto" x:Name="ImageButtonControl">
<Button>
    <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
        <Image Source="{Binding Image, ElementName=ImageButtonControl}"
               Width="16" Height="16"
           Margin="5,0,0,0" VerticalAlignment="Center"/>
        <TextBlock Text="{Binding Text, ElementName=ImageButtonControl}"
           Margin="5,0,0,0" VerticalAlignment="Center"/>
    </StackPanel>
</Button>

This is working fine except for the StackPanel doesn't stretch to fill the width or the height! I've tried a Grid in it's place but to no avail. Any ideas where I'm going wrong?

Example:

Example


Solution

  • If you want to align the Button content to the left then you have to set the HorizontalContentAlignment of the button

       <Button HorizontalContentAlignment="Left" VerticalContentAlignment="Center">
            <StackPanel Orientation="Horizontal" HorizontalAlignment="Stretch">
                <Image Source="{Binding Image, ElementName=ImageButtonControl}"
               Width="16" Height="16"
           Margin="5,0,0,0" VerticalAlignment="Center"/>
                <TextBlock Text="{Binding Text, ElementName=ImageButtonControl}"
           Margin="5,0,0,0" VerticalAlignment="Center"/>
            </StackPanel>
        </Button>