如何强制Grid缩小包含ScrollViewer的自动调整大小的行(如果需要)?

时间:2014-08-01 10:18:30

标签: wpf layout grid scrollviewer

我是WPF的新手。 我想制作这个简单的布局而我无法做到。让我为你画画:

How it should work

当没有足够的空间时,想法是将蓝色文本始终保持在绿色元素下面但是绿色元素应放在可滚动容器内(可见垂直滚动条)。

我尝试过StackPanel和Grid,但都失败了。 StackPanel根本不收缩行。如果顶部RowDefinition的高度设置为“auto”(内部的ScrollViewer不显示其滚动条),Grid会执行相同的操作。如果它设置为星形,则蓝色文本向下移动到至少一半的空间(取决于底行的高度设置)。底行的高度可以是“自动”或星形,蓝色文本的VerticalAlignment设置为Top但是行的高度必须保持至少与文本一样大。当然整个区域(黑匣子)的内容不能拉伸 - 它取决于窗户的大小。

如果您知道如何使其正常工作,请提供帮助。如果你愿意,可以在XAML中发布。谢谢!

2 个答案:

答案 0 :(得分:10)

受到Eirik通过将贪婪容器放入其他紧凑容器来约束贪婪容器的方法的启发,我发现了一种实现我想要的非常简单的方法。我只需要一个容器,它首先缩小它的一个孩子,然后(当第一个完全消失时)第二个。还有这样的容器:DockPanel。这是:

<DockPanel LastChildFill="False">
    <DockPanel DockPanel.Dock="Top">
        <TextBlock DockPanel.Dock="Bottom" TextWrapping="Wrap" Grid.Row="1">Automatically wrapped text of unknown length.</TextBlock>
        <ScrollViewer>
            <TextBlock TextWrapping="Wrap">In this case the element is too big to fit inside whole space (the black box) with the blue text below. I want the scrollbar to be shown instead of moving the blue text outside of the black box (and clipped)</TextBlock>
        </ScrollViewer>
    </DockPanel>
</DockPanel>

就这么简单! :)我希望它可以帮到某人。

答案 1 :(得分:3)

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

    <Canvas>
        <Grid MaxWidth="{Binding ElementName=outerGrid, Path=ActualWidth}" MaxHeight="{Binding ElementName=outerGrid, Path=ActualHeight}">
            <Grid.RowDefinitions>
                <RowDefinition Height="*"></RowDefinition>
                <RowDefinition Height="Auto"></RowDefinition>
            </Grid.RowDefinitions>
            <ScrollViewer Width="{Binding ElementName=outerGrid, Path=ActualWidth}">
                <TextBlock TextWrapping="Wrap">In this case the element is too big to fit inside whole space (the black box) with the blue text below. I want the scrollbar to be shown instead of moving the blue text outside of the black box (and clipped)</TextBlock>
            </ScrollViewer>
            <TextBlock TextWrapping="Wrap" Grid.Row="1">Automatically wrapped text of unknown length.</TextBlock>
        </Grid>
    </Canvas>
</Grid>

自动高度将增长以匹配该行内容的高度。

星形高度会让该行的高度增加,以填充网格的其余高度,从而防止ScrollViewer增长超过可见的行。

编辑:如果您将网格放在另一个网格中,就像上面的XAML一样,您应该获得所需的行为。 外排的第二行充当“填充物”,以填充外部网格的其余空间。

编辑2 :尝试上面编辑过的XAML。我将内部Grid置于Canvas内(以防止剪裁),并将内部MaxWidth的{​​{1}}和MaxHeight绑定到{{1}外部Grid的{​​}和ActualWidth以及内部ActualHeight与外部Grid的大小相同。

编辑3 :添加了与Grid的{​​{1}}的绑定,以使其与其余部分保持相同的宽度。