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

GilShalit picture GilShalit · Jul 13, 2011 · Viewed 44.5k times · Source

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?

Answer

Rachel picture Rachel · Jul 13, 2011

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.