Sunday, May 03, 2009

WPF: StackPanel vs DockPanel and ScrollViewer

Mucking around with WPF (Microsoft's latest and nicest way of putting GUIs together), I spent an hour googling to find the following gem.

A StackPanel allows its children to occupy whatever space they need. Therefore, you will never see a scroll bar you have attached (via a ScrollViewer) to a child of a StackPanel unless you have explicitly set the ScrollViewer Height property. You won't see the scroll bar because the child will be under the impression it has all the room it needs.

A DockPanel, on the other hand, requests that its children limit themselves to the area in the window occupied by the DockPanel.

On the left you can see an application where a ScrollViewer is attached to a StackPanel in a child of a DockPanel. The scroll bar is visible because the StackPanel cannot be fully displayed in the area made available by the DockPanel. The document structure looks something like this:

DockPanel
...
TabControl DockPanel.Dock=Top
TabItem
ScrollViewer
StackPanel



On the right you can see the same application where the ScrollViewer's parent is a child of a StackPanel. The scroll bar is not shown because the child StackPanel thinks it has all the display area it needs. This document structure looks something like this:

StackPanel
...
TabControl DockPanel.Dock=Top
TabItem
ScrollViewer
StackPanel


No comments: