WPF Grid行高为*时无法扩展至MaxHeight问题求助
WPF Grid 行自适应与MaxHeight生效问题解决方案
问题核心
你设置的*行高是按比例分配Grid的剩余空间,但当某行的ContentControl无内容时,该行的*比例逻辑仍会让Grid为其预留"比例空间",导致Grid总高度无法达到MaxHeight=500。
解决方案一:使用值转换器动态调整行高
通过自定义值转换器,根据ContentControl的内容是否为空,动态设置对应行的高度:
- 后台定义转换器:
public class ContentToRowHeightConverter : IValueConverter { public object Convert(object value, Type targetType, object parameter, CultureInfo culture) { return value == null ? new GridLength(0) : new GridLength(1, GridUnitType.Star); } public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) { throw new NotImplementedException(); } }
- XAML中引用并绑定:
<Window.Resources> <local:ContentToRowHeightConverter x:Key="ContentToRowHeightConverter"/> </Window.Resources> <Grid MaxHeight="500"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="{Binding ElementName=cc1, Path=Content, Converter={StaticResource ContentToRowHeightConverter}}"/> <RowDefinition Height="{Binding ElementName=cc2, Path=Content, Converter={StaticResource ContentToRowHeightConverter}}"/> </Grid.RowDefinitions> <Button Grid.Row="0" Content="SwitchGrid"/> <ContentControl x:Name="cc1" Grid.Row="1" Content="{Binding DG1}"/> <ContentControl x:Name="cc2" Grid.Row="2" Content="{Binding DG2}"/> </Grid>
解决方案二:纯XAML用DataTrigger实现
无需后台代码,通过DataTrigger监听ContentControl的HasContent属性,动态修改行高:
<Grid MaxHeight="500"> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition x:Name="Row1" Height="*"/> <RowDefinition x:Name="Row2" Height="*"/> </Grid.RowDefinitions> <Button Grid.Row="0" Content="SwitchGrid"/> <ContentControl x:Name="cc1" Grid.Row="1" Content="{Binding DG1}"/> <ContentControl x:Name="cc2" Grid.Row="2" Content="{Binding DG2}"/> <Grid.Style> <Style TargetType="Grid"> <Style.Triggers> <DataTrigger Binding="{Binding ElementName=cc1, Path=HasContent}" Value="False"> <Setter TargetName="Row1" Property="Height" Value="0"/> </DataTrigger> <DataTrigger Binding="{Binding ElementName=cc2, Path=HasContent}" Value="False"> <Setter TargetName="Row2" Property="Height" Value="0"/> </DataTrigger> </Style.Triggers> </Style> </Grid.Style> </Grid>
原理说明
当ContentControl无内容时,将对应行的高度设为0,剩余有内容的*行就会自动占满MaxHeight减去Auto行高度后的所有空间,从而让Grid扩展到最大允许高度。
内容的提问来源于stack exchange,提问作者RDV
相关产品推荐
相关产品推荐

