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!
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.
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".
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With