The button below always expands to be as wide as the TextBlock. I’ve tried StackPanel, DockPanel, Width=’Auto’, etc.
How can I make the button expand to the size of its own text (as in HTML) and not to the size of text in its environement?
<DockPanel HorizontalAlignment='Left'> <Button x:Name='ButtonFavorite' DockPanel.Dock='Top' Content='Customers' Margin='10' Width='Auto' Click='ButtonFavorite_Click'> </Button> <TextBlock DockPanel.Dock='Top' Text='this is a long text which makes the button stretch across the window, if this text is just a couple words, the button will be smaller, and this drives me up the wall' Margin='10' TextWrapping='Wrap' /> </DockPanel>
ANSWER:
Thanks Greg, that did it. Here is the full XAML that works now, you can right-click the button to change its Content so see that the button expands and contracts appropriately.
<Window x:Class='Test3784234.Window1' xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' xmlns:x='http://schemas.microsoft.com/winfx/2006/xaml' Title='Window1' Height='300' Width='300'> <DockPanel HorizontalAlignment='Left'> <StackPanel DockPanel.Dock='Top' Orientation='Horizontal' > <Button x:Name='ButtonFavorite' Padding='5' Cursor='Hand' DockPanel.Dock='Top' Content='Customers' Margin='10' Click='ButtonFavorite_Click'> <Button.ContextMenu> <ContextMenu> <MenuItem x:Name='menuItemReports' Header='Reports' Click='MenuItem_Click' /> <MenuItem x:Name='menuItemContracts' Header='Contracts' Click='MenuItem_Click'/> <MenuItem x:Name='menuItemCustomers' Header='Customers' Click='MenuItem_Click' /> <MenuItem x:Name='menuItemDocumentation' Header='Documentation Creation Instructions' Click='MenuItem_Click' /> <MenuItem x:Name='menuItemEmail' Header='E-Mail' Click='MenuItem_Click' /> </ContextMenu> </Button.ContextMenu> </Button> </StackPanel> <TextBlock x:Name='TheMessage' DockPanel.Dock='Top' Text='Right-click the 'favorites' button to change its function.' Margin='10' TextWrapping='Wrap'/> </DockPanel> </Window>
Regarding your annoyance at the sizing of buttons, this is something that seems to be targeted at the designer in the designer/developer workflow, while you’re clearly working on the developer portion. For the sake of development, I always apply a few styles in my App.xaml to ensure somewhat better button sizing. For example, in the application tag in your app.xaml file:
Regarding your actual question:
The problem is that your DockPanel is stretching to the width of the text and the button will naturally expand to fill the available area. If you want the quick and dirty solution you can do something like:
Note the MaxWidth. If you want a more composable result, isolate your button in another panel. (I’m using a stackpanel because I believe someone else already used a grid in their example):
I like the StackPanel in this case because I find myself using it to create the horizontal ‘bar’ of buttons along the bottom of a Form- err- Window in the right corner.