如何在不指定静态高度或宽度的情况下使滚动查看器工作



我目前正在为 WPF 应用程序开发 UI,我想使用 ScrollViewer 来显示可能超出屏幕查看区域的内容。

在过去的两天里,我已经阅读了整个互联网,据我所知:除非静态确定,否则 ScrollViewer 不知道它的内容/父级的高度;因此,如果没有写下特定的高度(例如,在它下面的 StackPanel 的情况下(,它不允许滚动。

现在,假设我的 UI 层次结构如下所示:

<Window> <!--No height here-->
    <Grid>
        <StackPanel Orientation="Horizontal"/>
        <ContentControl>
            <UserControl> <!--This user control doesn't have a specific height or width-->
                <Grid>
                    <ScrollViewer>
                        <Grid /> <!--This grid doesn't contain any StackPanels, or containers with dynamic height, and this is content I want to show-->
                    </ScrollViewer>
                    <Grid />
                </Grid>
            </UserControl>
        </ContentControl>
    </Grid>
</Window>

我希望 ScrollViewer 能够适当地滚动,因为它下面没有动态容器,但它没有,而且似乎为它或它上面的用户控件设置静态高度可以使其工作。

但是由于该应用程序可以在不同的屏幕尺寸上运行,并且所有窗口都可以以某种方式调整大小,因此我不想编写静态尺寸。

解决方案是为网格使用分数大小(以某种方式提供滚动查看器高度(,例如:

<Grid>
  <Grid.RowDefinitions>
    <RowDefinition Height="*"/>
    <RowDefinition Height="Auto" /> <!--this gives the second row the space it needs and leaves the scrollviewer with all the remaining space, this will also work if you need to make the second row child fixed-->
  </Grid.RowDefinitions>
  <ScrollViewer Grid.Row="0"/>
  <Grid Grid.Row="1"/>
</Grid>

若要获得更好的网格体验,请使用 WpfAutoGrid。

最新更新