简体   繁体   中英

WPF shrink other conent when Expander is Expanded

Whenever Expander is expanded I would like to shrink grid cell above containing ListBox , so that you can always access every ListItem(if the listbox's grid cell would not shrink, lowest part would be inacessible). To illustrate:

item              item *scrollbar* 
item          ->  item *scrollbar*  
item              expanderItems
expander          expander

I found bunch of threads for resizable expander, but none mentioning resizing other content. The problem is, grid containing listbox in 1st row and expander in 2nd with 2nd row Height set to Auto do not resize itself when expander is expanded.

<Grid.RowDefinitions>
    <RowDefinition Height="1*"/>
    <RowDefinition Height="Auto"/>
</Grid.RowDefinitions>

I managed to code an ugly workaround using Expanded/Collapsed events:

private void Expander_Expanded(object sender, System.Windows.RoutedEventArgs e)
{
    //grid1.Height is named content of expander
    this.LayoutRoot.RowDefinitions[1].Height = new GridLength(this.LayoutRoot.RowDefinitions[1].ActualHeight + grid1.Height, GridUnitType.Pixel);
    this.LayoutRoot.RowDefinitions[0].Height = new GridLength(1, GridUnitType.Star);
}

What would be the proper way? Preferably with no code behind and more "automated".
EDIT: xaml

<Grid x:Name="LayoutRoot">
    <Grid.RowDefinitions>
        <RowDefinition Height="1*"/>
        <RowDefinition Height="Auto"/>
    </Grid.RowDefinitions>
    <Expander Header="Expander" Margin="0" Grid.Row="1" VerticalAlignment="Bottom" Height="23" Panel.ZIndex="1" ExpandDirection="Up" Grid.RowSpan="2" Expanded="Expander_Expanded" Collapsed="Expander_Collapsed">
        <Grid x:Name="grid1" Background="#FF762CF7" Height="100" Margin="0,-100,0,0"/>
    </Expander>
    <ListBox Margin="0" Background="#19FFFFFF">
        <Button Height="150" Width="100"/>
        <Button Height="150" Width="100"/>
        <Button Height="150" Width="100"/>
    </ListBox>
    <Grid Margin="0" Grid.Row="1" Background="#FFAEFFAE"/>
    <Grid Margin="0" Background="#FFFFD8D8"/>
</Grid>

The main problem you have is setting the Height property of the Expander. It changes its height when you expand it. But if you are setting it, it has to respect the height you gave it and cannot properly expand.

Instead of setting the Height , I would set the MinHeight (or completely remove height constraints, depending on what you want to do).

Additionally you should remove the Margin of the grid inside the expander.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM