使带有扩展器的网格适应可用高度



>我有一堆彼此重叠的扩展器,可以独立打开/关闭。

除一个外,所有都有固定高度(展开时)。另一个有一个MinHeight,但我希望它拉伸以填充剩余的可用高度。如果扩展器的组合高度大于可用高度,则会显示滚动条。

我已经使用了一个Grid,每个网格有一个扩展器,并且该行Height设置为拉伸扩展器的*,而其他扩展器的行Auto

除了一种情况外,这工作正常:如果弹性扩展器折叠,并且其他扩展器的总高度小于可用高度,那么拉伸扩展器无论如何都会填充剩余空间,只是它的内容折叠,所以我得到一大块背景颜色。

我也尝试过StackPanel或嵌套网格,但如果不创建其他网格,就无法解决这个问题。

有什么想法吗?

(将其粘贴到窗口中)

<ScrollViewer>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="*" MinHeight="23"/>
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Expander IsExpanded="False" Grid.Row="0" Header="Fixed">
<Border Background="Red" Height="200" />
</Expander>
<Expander IsExpanded="False" Grid.Row="1" Header="Stretchy">
<Border Background="Blue" />
</Expander>
<Expander IsExpanded="False" Grid.Row="2" Header="Fixed">
<Border Background="Green" Height="300" />
</Expander>
</Grid>
</ScrollViewer>

默认情况下,扩展器占用所有可用空间。它通过将VerticalAlignmentHorizontalAlignment设置为Stretch来实现此目的。

要解决您的问题,请将VerticalAlignment设置为Top。然后扩展器只占用它需要的空间。

XAML 将如下所示:

<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="auto" />
<RowDefinition Height="auto" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Expander Grid.Row="0" Background="Green">
<Button Height="50">test</Button>
</Expander>
<Expander Grid.Row="1" Background="Red">
<Button Height="50">test</Button>
</Expander>
<Expander Grid.Row="2" Background="Blue" VerticalAlignment="Top">
<Button Height="50">test</Button>
</Expander>
</Grid>

编辑:

您应该将第二行的Height绑定到弹性扩展器的IsExpanded。如果已展开,请将其设置为*,如果没有,请将其设置为auto。您可以使用ValueConverter来执行此操作。

编辑2:

正如承诺的那样,解决您问题的标记和值转换器:

<ScrollViewer>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="Auto"/>
<RowDefinition Height="{Binding ElementName=Stretchy, Path=IsExpanded, Converter={StaticResource converter}}" MinHeight="23" />
<RowDefinition Height="Auto"/>
</Grid.RowDefinitions>
<Expander IsExpanded="False" Grid.Row="0" Header="Fixed">
<Border Background="Red" Height="200" />
</Expander>
<Expander x:Name="Stretchy" IsExpanded="False" Grid.Row="1" Header="Stretchy" VerticalAlignment="Stretch" MinHeight="100">
<Border Background="Blue" />
</Expander>
<Expander IsExpanded="False" Grid.Row="2" Header="Fixed">
<Border Background="Green" Height="300" />
</Expander>
</Grid>
</ScrollViewer>

价值转换器:

public class BoolToHeightConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
bool? v = value as bool?;
if (v == false)
return new GridLength(1, GridUnitType.Auto);
else
return new GridLength(1, GridUnitType.Star);
}
public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
throw new NotImplementedException();
}
}

最新更新