仅按内容填充容器

时间:2015-07-30 15:14:34

标签: wpf wpf-controls

我正面临布局问题。我需要创建一个窗口,其布局适用于以下两种情况:

enter image description here

我尝试使用DockPanel,但这样黄色容器即使没有内容也会拉伸。我需要对内容(UserControl)做一些事情来实现它。

编辑:“图片”内容固定为“=”内容固定高度“

2 个答案:

答案 0 :(得分:0)

使用自定义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>
    <stackOverflow:BoolToGridLengthConverter x:Key="BoolToGridSizeConverter" TrueLength="1*" FalseLength="Auto"/>
    <stackOverflow: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>

答案 1 :(得分:0)

我猜你可以使用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();
    }
}