据我了解,Grid 是一个容器,这意味着 Grid 在实际内容之前呈现。从技术上讲,不可能根据内容设置动态高度/宽度(除非您设置为自动)。通常这种情况可以通过控制控件的宽度/高度来克服,而不是解决复杂的解决方案。简而言之,假设您有 3 个控件,并且必须渲染 2 个控件中的任何一个,这必须同样占据页面宽度/高度,您可以将网格行高设置为自动,同时设置内容高度。可以参考父控件的实际宽度。
这里是示例供参考。在这个例子中,我假设你有一些机制来指导网格现在有多少用户控件是可见的。所以在converterParameter中传递项目计数。
public class HeightConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
int.TryParse(parameter.ToString(), out var items);
double.TryParse(value.ToString(), out var actualheight);
return actualheight / items;
}
//......
}
<Window.Resources>
<local:HeightConverter x:Key="HeightConverter"/>
</Window.Resources>
<Grid x:Name="mainGrid" Background="Gray">
<Grid.RowDefinitions>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="auto"/>
</Grid.RowDefinitions>
<local:sampleControl Background="Red" Grid.Row="0" Height="{Binding ElementName=mainGrid, Path=ActualHeight, Converter={StaticResource HeightConverter}, ConverterParameter=3}"/>
<local:sampleControl Background="Yellow" Grid.Row="1" Height="{Binding ElementName=mainGrid, Path=ActualHeight, Converter={StaticResource HeightConverter}, ConverterParameter=3}"/>
<local:sampleControl Background="Blue" Grid.Row="2" Height="{Binding ElementName=mainGrid, Path=ActualHeight, Converter={StaticResource HeightConverter}, ConverterParameter=3}"/>
</Grid>