2023年6月20日

Fill remaining space of parent with 2 or more expanders WPF

作者 dikangqie

c# – Fill remaining space of parent with 2 or more expanders WPF – Stack Overflow

You can achieve what you want using pure XAML if using a Grid instead of DockPanel. I don’t see the purpose of using DockPanel in this case. Otherwise you need code behind (some Converter) to resize the Expanders correctly.

The idea here is we need a Grid having 2 rows, when the contained Expander is collapsed, the row’s Height should be Auto, otherwise the row’s Height should be *. When the 2 Expanders are expanded, both the rows have Height of * and each one will share half the whole Height of the Grid:

<Grid Background="Black">
      <Grid.Resources>
         <Style TargetType="RowDefinition">
             <Setter Property="Height" Value="Auto"/>
             <Style.Triggers>
                 <DataTrigger Binding="{Binding Tag.IsExpanded, RelativeSource={RelativeSource Self}}" 
                              Value="True">
                     <Setter Property="Height" Value="*"/>
                 </DataTrigger>
             </Style.Triggers>
         </Style>
      </Grid.Resources>
      <Grid.RowDefinitions>
         <RowDefinition Tag="{Binding ElementName=articlesExpander}"/>
         <RowDefinition Tag="{Binding ElementName=turneroExpander}"/>
      </Grid.RowDefinitions>
      <Expander Name="articlesExpander" Template="{StaticResource ExpanderHeaderImage}">
            <Grid Name="articlesGridExpander" ShowGridLines="True" Background="#FFEC0000">
              <TextBlock>Hello</TextBlock>
            </Grid>
      </Expander>
      <Expander Name="turneroExpander" Template="{StaticResource ExpanderHeaderImage}" Grid.Row="1">
            <Grid Name="turneroGridExpander" ShowGridLines="True" Height="{Binding ElementName=DummyExpanderHeight, Path=Height}" Background="#FF0AE400">
               <TextBlock>Bye</TextBlock>
            </Grid>
      </Expander>
 </Grid>