使容器仅按内容填充

Make container fill only by content

我遇到布局问题。我需要制作一个 Window 的布局,适用于这两种情况:

我尝试使用 DockPanel 进行一些操作,但即使没有内容,黄色容器也会拉伸。我需要对实现它的内容(用户控件)做一些事情。

编辑: "Image's "内容固定为" = "CONTENT FIXED HEIGHT"

使用自定义 IValueConverter 根据中间控件是否有任何内容来切换行上的高度值

自定义 IValueConverter:

public class BoolToGridLengthConverter : IValueConverter
{
    public GridLength TrueLength { get; set; }

    public GridLength FalseLength { get; set; } 

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (bool)value ? TrueLength : FalseLength;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

XAML:

<UserControl.Resources>
    <Whosebug:BoolToGridLengthConverter x:Key="BoolToGridSizeConverter" TrueLength="1*" FalseLength="Auto"/>
    <Whosebug:BoolToGridLengthConverter x:Key="BoolToGridSizeConverter2" TrueLength="0" FalseLength="1*"/>
</UserControl.Resources>
<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto"/>
        <RowDefinition Height="{Binding ElementName=ChangingSizeControl, Path=HasContent, Converter={StaticResource BoolToGridSizeConverter}}"/>
        <RowDefinition Height="{Binding ElementName=ChangingSizeControl, Path=HasContent, Converter={StaticResource BoolToGridSizeConverter2}}"/>
    </Grid.RowDefinitions>
    <UserControl Grid.Row="0" x:Name="FixedSizeControl"/>
    <ContentControl Grid.Row="1" x:Name="ChangingSizeControl"/>
    <UserControl Grid.Row="2" x:Name="MainContentControl"/>
</Grid>

我猜你可以使用 IValueConverter 来...

<Grid>
    <Grid.Resources>
        <converters:NullableToVerticalAlignment FalseAlignment="Top" 
                                                TrueAlignment="Stretch" />
    </Grid.Resources>

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

    <custom:ContentWithFixedHeight />

    <custom:ContentWithVariableHeight Grid.Row="1"
                                      VerticalAlignment="{Binding Content,
                                                                  RelativeSource={RelativeSource Mode=Self},
                                      Converter={StaticResource NullableToVerticalAlignmentConverter}}" />
</Grid>

以及转换器本身:

public class BooleanToVerticalAlignment : IValueConverter
{
    public VerticalAlignment FalseAlignment { get; set; }

    public VerticalAlignment TrueAlignment { get; set; }

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        return (bool)value ? TrueAlignment : FalseAlignment;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}