在wpf中如何使datagrid适合窗口高度

Gil*_*lit 17 wpf datagrid scrollbar wpf-controls

我有一个3列2行的网格

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
Run Code Online (Sandbox Code Playgroud)

我左下角的单元格,我有一个数据网格,AutoGenerateColumns = True,可以加载很多行.我想要做的是使数据网格高度最大化以适应窗口,并且用户能够使用数据网格滚动条来上下滚动行.

会发生什么是数据网格流动的窗口底部,即使我设置了

ScrollViewer.VerticalScrollBarVisibility="Visible"
Run Code Online (Sandbox Code Playgroud)

对于datagrid,滚动条无效,行向下流动.不知何故,数据网格不受限制......

该怎么办?

Rac*_*hel 39

尝试设置你的DataGrid HorizontalAlignment=StretchVerticalScrollBarVisibility=Auto

如果这不起作用,您可能还需要将网格的高度绑定到窗口高度,以便它不会自动增长以适合其内容.通常我会使用Height="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=ActualHeight}"(它可能RenderSize.ActualHeight不仅仅是ActualHeight......我忘了.

另一种选择是使用a DockPanel而不是a,Grid因为该控件不会自动增长以适应其内容.相反,它会伸展它的最后一个孩子来填补剩余的空间.

  • 绑定技术的工作原理很吸引人,谢谢!如您所写,它是ActualPath。顺便说一句,我如何将某些东西绑定到路径值的一部分?Path = ActualPath / 2似乎不起作用。 (2认同)
  • @Gilshalit你需要使用转换器 (2认同)

小智 6

我遇到了同样的问题,但绑定到窗口高度并没有完全解决我的问题。在我的例子中,DataGrid 仍然延伸到窗口可视区域下方 2 到 3 英寸。我相信这是因为我的 DataGrid 开始于窗口顶部下方约 2 到 3 英寸处。

最后我发现根本没有必要绑定DataGrid的高度。我所要做的就是更改 DataGrid 的直接容器。

对我来说,当添加足够的行时,以下 XAML 设置会导致 DataGrid 超出窗口的大小。请注意,DataGrid 位于 StackPanel 内。

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="75"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <StackPanel Grid.Row="0">
       <!-- StackPanel Content accounting for about 2-3 inches of space -->
    </StackPanel>
    <!-- DataGrid within a StackPanel extends past the vertical space of the Window
     and does not display vertical scroll bars.  Even if I bind the height to Window 
     height the DataGrid content still extends 2-3 inches past the viewable Window area-->
    <StackPanel Grid.Row="1">
    <DataGrid ItemsSource="{StaticResource ImportedTransactionList}" 
         Margin="10,20,10,10" MinHeight="100">
    </DataGrid>
    </StackPanel>
</Grid>
Run Code Online (Sandbox Code Playgroud)

然而,简单地删除 StackPanel 就解决了我的问题。

<Grid>
    <Grid.RowDefinitions>
        <RowDefinition Height="75"/>
        <RowDefinition Height="*"/>
    </Grid.RowDefinitions>
    <StackPanel Grid.Row="0">
       <!-- StackPanel Content accounting for about 2-3 inches of space -->
    </StackPanel>
    <!-- Removing the StackPanel fixes the issue-->
    <DataGrid Grid.Row="1" ItemsSource="{StaticResource SomeStaticResource}" 
           Margin="10,20,10,10" MinHeight="100">
    </DataGrid>
</Grid>
Run Code Online (Sandbox Code Playgroud)

由于原始帖子相当旧,我应该注意到我正在使用 VS2017 和 .Net Framework 4.6.1,但我不确定这是否有任何影响。