Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set Button Size to Content Size in WPF Application

Tags:

I have the following code in WPF XAML:

<Window x:Class="WPFDemo.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">

    <StackPanel>
        <Button Content="Hello World" Width="Auto" Height="Auto"></Button>
    </StackPanel>


</Window>

I have set the width and height of the Button to "Auto" but still it stretches the complete horizontal width. What am I doing wrong? I do not want to provide a hardcoded values for the width and height!

like image 231
john doe Avatar asked Jul 07 '14 14:07

john doe


2 Answers

You are using the wrong kind of container control. The StackPanel does not resize its contents. Try a Grid instead:

<Grid>
    <Button Content="Hello" HorizontalAlignment="Center" VerticalAlignment="Center" />
</Grid>

Also, you don't need to set the Width and Height to "Auto", as the default values will enable the Button to stretch to fill its parent container (depending on the container control). Please see the Panels Overview page on MSDN for more help with the differences between the various container controls in WPF.

like image 85
Sheridan Avatar answered Sep 18 '22 14:09

Sheridan


As Sheridan said, you do not need to set Width and Height to "Auto". Your problem is that the default alignment of the StackPanel content is "Stretch". So just set the HorizontalAlignment property of your button to "Left" or "Right".

like image 40
Golvellius Avatar answered Sep 16 '22 14:09

Golvellius