Wpf – Why does this WPF button stretch across the window

wpfxaml

The button below always expands to be as wide as the TextBlock. I've tried StackPanel, DockPanel, Width="Auto", etc.

How can I make the button expand to the size of its own text (as in HTML) and not to the size of text in its environement?

    <DockPanel HorizontalAlignment="Left">
        <Button x:Name="ButtonFavorite"
                DockPanel.Dock="Top"  
                Content="Customers" 
                Margin="10" 
                Width="Auto"
                Click="ButtonFavorite_Click">
        </Button>

        <TextBlock DockPanel.Dock="Top" Text="this is a long text which makes the button stretch across the window, if this text is just a couple words, the button will be smaller, and this drives me up the wall"  Margin="10" TextWrapping="Wrap" />

    </DockPanel>

ANSWER:

Thanks Greg, that did it. Here is the full XAML that works now, you can right-click the button to change its Content so see that the button expands and contracts appropriately.

<Window x:Class="Test3784234.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Window1" Height="300" Width="300">
    <DockPanel HorizontalAlignment="Left">
        <StackPanel DockPanel.Dock="Top" Orientation="Horizontal" >
            <Button x:Name="ButtonFavorite"
                    Padding="5"
                    Cursor="Hand" 
                    DockPanel.Dock="Top"  
                    Content="Customers" 
                    Margin="10" 
                    Click="ButtonFavorite_Click">
                <Button.ContextMenu>
                    <ContextMenu>
                        <MenuItem x:Name="menuItemReports" Header="Reports" Click="MenuItem_Click" />
                        <MenuItem x:Name="menuItemContracts" Header="Contracts" Click="MenuItem_Click"/>
                        <MenuItem x:Name="menuItemCustomers" Header="Customers" Click="MenuItem_Click" />
                        <MenuItem x:Name="menuItemDocumentation" Header="Documentation Creation Instructions" Click="MenuItem_Click" />
                        <MenuItem x:Name="menuItemEmail" Header="E-Mail" Click="MenuItem_Click" />
                    </ContextMenu>
                </Button.ContextMenu>
            </Button>

        </StackPanel>

        <TextBlock x:Name="TheMessage" DockPanel.Dock="Top" Text="Right-click the 'favorites' button to change its function." Margin="10" TextWrapping="Wrap"/>

    </DockPanel>
</Window>

Best Answer

All you need to do is set the HorizontalAlignment property on your button. It defaults to stretch therefore filling the available space.

<Button x:Name="ButtonFavorite"
        HorizontalAlignment="Left"
        Content="Customers" 
        Margin="10" 
        Width="Auto"
        Click="ButtonFavorite_Click">
Related Topic