DaveDev
DaveDev

Reputation: 42175

How to create a button that will increase its width depending on the amount of text in it?

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

Answers (2)

Agustin Meriles
Agustin Meriles

Reputation: 4854

Just set the Width property to Auto and give an HorizontalAlignment (Center, Rightor 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

enter image description here

Upvotes: 2

NthDeveloper
NthDeveloper

Reputation: 1009

I you don^t set a fixed width to your button, it will already adapt its width to its content.

Upvotes: 2

Related Questions