Keeping WPF grids from getting out of parent bounds

722 Views Asked by At

In my UI, I have a big grid with two columns and one row. in the right column, I have a grid with three rows where in the top row I have a user control, and in the two bottom rows I have two Expander objects, each containing an ItemsControl with a list that gets populated in runtime. Sometimes, that list gets really long and "spills" from the screen towards the bottom.

What I want to do is to allow the user to see both expanders, be able to expand or collapse them while keeping them both in sight. I tried wrapping them in WrapPanels or StackPanel but to no avail.

Here's some code to help explain my problem:

<Grid Grid.Row="1" x:Name="grid1">
<Grid.RowDefinitions>
    <RowDefinition Height="*" />
    <RowDefinition Height="*" />
</Grid.RowDefinitions>
<Expander Grid.Row="0" Header="Expander 1" x:Name="expander1" FontSize="14" IsExpanded="True">
    <Expander.Background>
        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
            <GradientStop Color="#FFC4C4C4" Offset="0" />
            <GradientStop Color="White" Offset="1" />
        </LinearGradientBrush>
    </Expander.Background>
    <ContentPresenter Content="{Binding ViewModel.OpenAlerts, ElementName=m_viewControl}" ClipToBounds="True"/>
</Expander>
<Expander Grid.Row="1" x:Name="expander2" Header="Expander 2" FontSize="14" IsExpanded="True">
    <Expander.Background>
        <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
            <GradientStop Color="#FFC4C4C4" Offset="0" />
            <GradientStop Color="White" Offset="1" />
        </LinearGradientBrush>
    </Expander.Background>
    <ContentPresenter Content="{Binding ViewModel.ClosedAlerts, ElementName=m_viewControl}" ClipToBounds="True"/>
</Expander>
</Grid>

Any assistance or tips will be highly appreciated!

Thanks, John.

1

There are 1 best solutions below

3
On

It's really not clear what kind of UI elements you have in the Expanders, but a ListBox for example works just fine, it will show scrollbars when the number of items is larger that the allocated space in the Grid row.

But you can also wrap you list of items in a StackPanel inside a ScrollViewer, which also works fine:

<Expander Grid.Row="0" Header="Expander 1" x:Name="expander1" FontSize="14" IsExpanded="True">
  <Expander.Background>
    <LinearGradientBrush EndPoint="0.5,1" StartPoint="0.5,0">
      <GradientStop Color="#FFC4C4C4" Offset="0" />
      <GradientStop Color="White" Offset="1" />
    </LinearGradientBrush>
  </Expander.Background>
  <ScrollViewer>
    <StackPanel>
      <TextBlock>Test</TextBlock>
      <TextBlock>Test</TextBlock>
      <TextBlock>Test</TextBlock>
      <!-- etc.. -->
      <!-- etc.. -->
    </StackPanel>
  </ScrollViewer>
</Expander>

That should also work for you.