Friday, December 10, 2010

WPF Tips and Tricks - DockPanel Doesn't Behave Right

Consider the following:

  1.   <DockPanel>
  2.       <ListBox Width="2000">
  3.         <!-- Lots of items -->
  4.       </ListBox>
  5.       <StackPanel DockPanel.Dock="Bottom" Height="35" Orientation="Horizontal" VerticalAlignment="Bottom" HorizontalAlignment="Right">
  6.           <Button VerticalAlignment="Center" HorizontalAlignment="Right">OK</Button>
  7.           <Button VerticalAlignment="Center" HorizontalAlignment="Right">Cancel</Button>
  8.       </StackPanel>    
  9.     </DockPanel>

You would think that the buttons at the bottom will always be there. But if that ListBox gets too many items, the DockPanel will happily cover up the StackPanel. That doesn't seem right since the StackPanel has an explicit height and it is explicitly docked to the bottom. The reason for this is the DockPanel renders items in the order they are entered. In this case, the ListBox gets rendered first and fills the space. The fix is simple, although does not reflect the real layout of the page. That is to flip the StackPanel and ListBox.

  1.   <DockPanel>
  2.       <StackPanel DockPanel.Dock="Bottom" Height="35" Orientation="Horizontal" VerticalAlignment="Bottom" HorizontalAlignment="Right">
  3.           <Button VerticalAlignment="Center" HorizontalAlignment="Right">OK</Button>
  4.           <Button VerticalAlignment="Center" HorizontalAlignment="Right">Cancel</Button>
  5.       </StackPanel>
  6.       <ListBox Width="2000">
  7.         <!-- Lots of items -->
  8.       </ListBox>
  9.     </DockPanel>