Search code examples
c#wpfmvvmdatagridrowcount

Add the Index Number of a ViewModel's members as Row Number in DataGrid


As of the moment, I am using the following code which calls my converter which does the thing for me, put the row number I need.

<DataGridTextColumn Header="NO" Width="22" IsReadOnly="True" x:Name="rowNumber">
                    <DataGridTextColumn.HeaderStyle>
                        <Style TargetType="{x:Type DataGridColumnHeader}">
                            <Setter Property="FontSize" Value="10" />
                            <Setter Property="Margin" Value="0"/>
                        </Style>
                    </DataGridTextColumn.HeaderStyle>
                    <DataGridTextColumn.Binding>
                        <MultiBinding Converter="{StaticResource rowNumberConverter}">
                            <Binding />
                            <Binding RelativeSource="{RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}" />
                        </MultiBinding>
                    </DataGridTextColumn.Binding>
                </DataGridTextColumn>

And the converter:

class RowNumberConverter : IMultiValueConverter
    {
        #region IMultiValueConverter Members

        public object Convert(object[] values, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {

            //get the grid and the item
            Object item = values[0];
            DataGrid grid = values[1] as DataGrid;

            int index = grid.Items.IndexOf(item) + 1 ;

            return index.ToString().PadLeft(2, '0');
        }

        public object[] ConvertBack(object value, Type[] targetTypes, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }

However, this would fail in our new requirement, pagination. This converter would of course not continue the count as it is only referencing the rows in the DataGrid.

Can anyone point me on how to make the row count continue on the next page? Sticking to clean MVVM pattern is necessary.

Thanks for your help.


Solution

  • I think of a view model simply as the element that supplies all of the data that it to be displayed. If there is a requirement to display item numbers, then simply add another property to the element being displayed.

    Doing it this way enables you to populate the numbers with whatever values you want, whether there are numbers in one continuous sequence, or whether you have a more complicated numbering system.