Breaking XAML Stretch with StackPanel

A StackPanel works great as far as stretching in one direction (opposite the orientation): it behaves just like a Star sized Grid with one row or column. The problem happens in the direction of the StackPanel’s Orientation, where it behaves as an infinitely sized container. This results in the StackPanel passing an available width or height of Infinity to each of its children, which for some types of elements can make it difficult to size properly. This can be easy to diagnose for direct children of the StackPanel and is often easy to fix. Unfortunately the problem is inherited by any child contained anywhere under the StackPanel and can become significantly harder to debug.

StackPanel children

In the case of direct children the fix can be straightforward but depends on the desired final layout. Let’s start with a simple example of a Horizontal StackPanel containing a TextBlock. In this case the text is too long to fit in the available space but even though TextWrapping is set to Wrap it stays on a single line and runs off the screen.

<StackPanel Orientation="Horizontal">
	<Button Content="Reset"/>
	<TextBlock TextWrapping="Wrap" FontSize="18">
		This is some long text that should wrap to a new line and not run out of the window.
	<Button Content="Submit"/>

Text fails to wrap in StackPanel

Read More