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

时间:2011-07-13 11:33:51

标签: wpf datagrid wpf-controls scrollbar

我有一个包含3列和2行的网格

        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="10"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>

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

当窗口底部的数据网格流动时,即使我设置了

,也会发生什么
ScrollViewer.VerticalScrollBarVisibility="Visible"
数据网格的

,滚动条无效,行向下流动。不知何故,数据网格不会受到限制......

怎么办?

3 个答案:

答案 0 :(得分:37)

尝试设置DataGrid的HorizontalAlignment=StretchVerticalScrollBarVisibility=Auto

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

另一种方法是使用DockPanel而不是Grid,因为该控件不会自动增长以适应其内容。相反,它会延长其最后一个孩子以填补剩余的空间。

答案 1 :(得分:1)

您必须定义DataGrid与*所在的列和行。 你说它在左下方的细胞上。该行没问题,但您的专栏有Width="Auto"

如果AutoGenerateColumns=TrueWidth="Auto"会造成混乱。

答案 2 :(得分:1)

我遇到了同样的问题,但是绑定到Window高度并不能完全解决我的问题。就我而言,DataGrid仍在窗口的可视区域下方延伸了2到3英寸。我相信这是因为我的DataGrid从窗口顶部下方开始大约2到3英寸。

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

对我来说,以下XAML设置会在添加足够的行时使DataGrid扩展到Window之外。请注意,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>

但是,只需删除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>

由于原始文章很老,我应该注意我正在使用VS2017和.Net Framework 4.6.1,但是我不确定这是否有影响。