in wpf how do i make a datagrid fit the window hei

2019-02-06 03:34发布

问题:

I have a grid with 3 columns and 2 rows

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

I the lower left cell, i have a data grid, with AutoGenerateColumns=True which can load many rows. What I want to do is for the data grid height to maximize to fit the window, and for the user to be able to use the datagrid scrollbar to scroll the rows up and down.

What happens is that the datagrid flows of the bottom of the window, and even if i set the

ScrollViewer.VerticalScrollBarVisibility="Visible"

of the datagrid, the scrollbar has no effect and the rows flow downwards. Somehow the datagrid does not feel restricted...

What to do?

回答1:

Try setting your DataGrid's HorizontalAlignment=Stretch and VerticalScrollBarVisibility=Auto

If that doesn't work, you may also need to bind the Grid's Height to the Window Height so that it doesn't auto-grow to fit its contents. Usually I use Height="{Binding RelativeSource={RelativeSource AncestorType={x:Type Window}}, Path=ActualHeight}" (It might be RenderSize.ActualHeight instead of just ActualHeight... I forgot.

Another alternative is to use a DockPanel instead of a Grid since that control doesn't auto-grow to fit its contents. Instead it'll stretch its last child to fill the remaining space.



回答2:

You have to define the column and row where the DataGrid is with *. You say it is on the lower left cell. The row is ok but your column there has Width="Auto".

The AutoGenerateColumns=True gives a mess if Width="Auto".