How to make button's width autofit the text of a button?
Solution 1
What you have to do is set the HorizontalAlignment property to Center (or Right or Left). The buttons must be getting stretched by the containing Panel.
<Style TargetType="{x:Type Button}">
<Setter Property="MinWidth" Value="90" />
<Setter Property="HorizontalAlignment" Value="Center" />
</Style>
Solution 2
If setting HorizontalAlignment
isn't working, check to see that you have not set a Width
- that will prevent the button from resizing. A handy trick is setting the Width
property to NaN
or ..NaN
depending upon your application's configuration (which ever doesn't throw a compilation error).
Solution 3
If you just set MinWidth of button and if your text width is bigger than min width it will automatically expand, but in reverse case button will be same with your min width,
<Style TargetType="{x:Type Button}">
<Setter Property="MinWidth" Value="90" />
</Style>
that is enough to archive to required result
Alex Baranosky
Check me out on Github too: https://github.com/alexbaranosky
Updated on November 08, 2020Comments
-
Alex Baranosky over 3 years
I am currently doing this, but I am doing something wrong :):
<Style TargetType="{x:Type Button}"> <Setter Property="MinWidth" Value="90" /> <Setter Property="Width" Value="Auto" /> </Style>
I want the buttons to have some minimum width but also to have their width expand to fit the text of the button.