Search code examples
wpfdatagriddatagridcolumn

How to fix number of lines to show in datagrid?


I want to display only 15 line in a datagrid and scrolling to get the rest of data. Meaning I have a datagrid Height which is variable and i want something like this row height = datagrid height /15.


Solution

  • Create a Border that contains a ScrollViewer that contains you DataGrid. Bind the RowHeight of the DataGrid with a MultiBinding to the ActualHeight of the Border and to the ColumnHeaderHeight of the DataGrid. To retrieve the value of the RowHeight use an IMultiValueConverter.

    The converter:

    using System;
    using System.Globalization;
    using System.Windows.Data;
    
    namespace XXX
    {
        public class HeightConverter : IMultiValueConverter
        {
            public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
            {
                double allHeight = (double)values[0];
                double headerHeight = (double)values[1];
    
                return (allHeight - headerHeight) / 15;
            }
    
            public object[] ConvertBack(object value, Type[] targetTypes, object parameter, CultureInfo culture)
            {
                throw new NotImplementedException();
            }
        }
    }
    

    And here the xaml:

      <Border Name="YourBorder">
        <ScrollViewer>
          <DataGrid Name="YourGrid"
                    ItemsSource="{Binding Items}"
                    Padding="0"
                    Margin="0"
                    ColumnHeaderHeight="30">
            <DataGrid.RowHeight>
              <MultiBinding Converter="{StaticResource HeightConverter}">
                <Binding Path="ActualHeight" ElementName="YourBorder"/>
                <Binding Path="ColumnHeaderHeight" ElementName="YourGrid"/>
              </MultiBinding>
            </DataGrid.RowHeight>
            <DataGrid.Columns>
              <!-- YOUR COLUMNS TEMPLATES - don't put fixed height here! -->
            </DataGrid.Columns>
          </DataGrid>
        </ScrollViewer>
      </Border>
    

    Items: a mock collection I've created to test this solution.

    ColumnHeaderHeight: you MUST set this or it'll be NaN. I've set 30 'cause it seems suitable for a normal header text, but check it by yourself if you have custom headers.

    When you stretch the window, you'll see that the rows resize, so they always remain 15 visible and the others remain reachable with the scrollbar.

    Hope this is what you were looking for.