I'm making a toolbar. I want the width of the window to equal the total width of the buttons. StackPanel seems perfect for the job because it lines everything up, but it won't stretch.
<Window Width="auto">
<StackPanel Orientation="Horizontal" Width="auto">
<Button />
<Button />
</StackPanel>
</Window>
How do I make this work?
I found a very simple solution! Almost everybody (I've been searching tons of pages) suggests switching control types or something much more complex, but in fact, it's much simpler:
<Window SizeToContent="Width"
That's the only change required.
The source of this bit: https://stackoverflow.com/a/2317914/971583, the second-ranked answer to the problem, which seems to me the better one.
You can make the width of the window to equal the total width of the buttons using a UniformGrid instead of a StackPanel.
<UniformGrid Margin="10" Rows="1" HorizontalAlignment="Right"
VerticalAlignment="Bottom">
<Button Grid.Column="0" Content="No" FontSize="18" Margin="5" Padding="6,3"/>
<Button Grid.Column="1" Content="Yes, Absolutely" Margin="5" Padding="6,3"/>
<Button Grid.Column="2" Content="Maybe" Margin="5" Padding="6,3"/>
</UniformGrid>
The UniformGrid provides eacg cell is the same height and the same width. This is what you want as you then avoid having to set the button sizes manually.
Update:
I would suggest not to use Stackpanel. Even if you make the Stackpanel fill its parent, its children still "stacks" and won't fill the Stackpanel.
Depending on your setting, you can achieve that simply using StackPanel's alignments. For example this XAML
<Window Width="350" Height="350" ...>
<Grid>
<StackPanel
Background="Green">
<Border
Width="100"
Height="100"
Background="Blue" />
<Border
Width="100"
Height="100"
Background="Red" />
</StackPanel>
</Grid>
</Window>
Will create this (the panel stretches to parent's size):
And this panel:
<Window Width="350" Height="350" ...>
<Grid>
<StackPanel
HorizontalAlignment="Center"
VerticalAlignment="Center"
Background="Green">
<Border
Width="100"
Height="100"
Background="Blue" />
<Border
Width="100"
Height="100"
Background="Red" />
</StackPanel>
</Grid>
</Window>
Will create this (sized to the two contained Borders):
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