WPF GridSplitter to split/resize two ListBox's?

Shafique picture Shafique · Sep 15, 2009 · Viewed 8.3k times · Source

I've got a grid that has 7 rows in it. Row 0 is a group of 2 buttons Row 1 is a ListBox of objects Row 2 is a group of 3 buttons Row 3 is a group of 2 buttons Row 4 is where my GridSplitter lives Row 5 is a group of 2 buttons Row 6 is a ListBox of objects

I want the GridSplitter to slide up and down, resizing each of the two ListBox's. I've got it living in its own row now, and when i Slide it, it freeze's when it gets to the top of row 4 (its own row) and simply creates white space while it expans row 4 downwards.

I just need that splitter to slide up and down and resize each ListBox. Currently those ListBoxes have vertical scrolling bars if they get too big for their view.

any ideas?

Answer

Drew Noakes picture Drew Noakes · Sep 15, 2009

Here's some XAML that shows how to use a GridSplitter as you've described:

<Grid VerticalAlignment="Stretch">  
  <Grid.RowDefinitions>
    <RowDefinition Height="10" />
    <RowDefinition Height="10" />
    <RowDefinition Height="10" />
    <RowDefinition Height="10" />
    <RowDefinition Height="10" />
    <RowDefinition Height="10" />
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
  </Grid.RowDefinitions>

  <Rectangle Grid.Row="0" Fill="Red" />
  <Rectangle Grid.Row="1" Fill="Orange" />
  <Rectangle Grid.Row="2" Fill="Yellow" />
  <Rectangle Grid.Row="3" Fill="Green" />
  <Rectangle Grid.Row="4" Fill="Blue" />
  <Rectangle Grid.Row="5" Fill="LightBlue" />

  <ListBox Grid.Row="6" Background="Indigo">
    <ListBoxItem>Hello</ListBoxItem>
    <ListBoxItem>World</ListBoxItem>
  </ListBox>

  <GridSplitter Grid.Row="7" Height="5" Background="Gray"
                VerticalAlignment="Top" HorizontalAlignment="Stretch" />

  <ListBox Grid.Row="7" Background="Violet" Margin="0,5,0,0">
    <ListBoxItem>Hello</ListBoxItem>
    <ListBoxItem>World</ListBoxItem>
  </ListBox>
</Grid>

Avoid putting the GridSplitter in it's own row. Put it inside an existing row, and set it's alignment to the top (or bottom, if in the upper cell), stretched horizontally. Note how I've set it's height to 5, and then given an upper margin of 5 to the second ListBox so that neither element hides any part of the other.

Hope that helps.