Reputation: 42175
I have a WPF window with a button on it. I want the button to increase or decrease in width depending on its text. How can I do this?
Upvotes: 0
Views: 296
Reputation: 4854
Just set the Width
property to Auto
and give an HorizontalAlignment (Center
, Right
or Left
), because its default value is Stretch
, and this cause to Fill its container.
Here is an example on how it works:
CODE
<Window x:Class="StackOverflow.WPF.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">
<Grid>
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Button Content="A Default Button"/>
<Button Content="An Auto Width Button"
Width="Auto"
HorizontalAlignment="Center"
Grid.Column="1"/>
<Button Content="An Auto Width and Height Button"
Width="Auto" Height="Auto"
HorizontalAlignment="Center"
VerticalAlignment="Center"
Grid.Column="0" Grid.Row="1"/>
</Grid>
</Window>
OUTPUT
Upvotes: 2
Reputation: 1009
I you don^t set a fixed width to your button, it will already adapt its width to its content.
Upvotes: 2