【问题标题】:How to make a ScrollViewer work without specifying a static height or width?如何在不指定静态高度或宽度的情况下使 ScrollViewer 工作?
【发布时间】:2019-06-18 00:24:15
【问题描述】:

我目前正在为 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 能够适当地滚动,因为它下面没有动态容器,但它没有,而且似乎为它或它上面的 UserControl 设置了一个静态高度使它工作。

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

【问题讨论】:

    标签: c# .net wpf xaml


    【解决方案1】:

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

    <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。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-08
      • 2021-09-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多