0

I have a DataGrid where the ItemsSource is bound to an ObservableCollection<LogEntry> in the ViewModel. In the DataGrid the properties Message and Date from the LogEntry-class are displayed.

The items in this ItemsSource are changing very often depending on an outer selection.

Now I want to introduce an additional column in my DataGrid which displays the row-number.

Is there a simple way to do this in WPF with MVVM or do I have to create a new class (e.g. RowLogEntry) which inherits from LogEntry and provides a property for the row-number?

Tomtom
  • 9,087
  • 7
  • 52
  • 95

1 Answers1

1

One way is to add them in the LoadingRow event for the DataGrid

 <DataGrid Name="DataGrid" LoadingRow="DataGrid_LoadingRow" ...

    void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
    {
        e.Row.Header = (e.Row.GetIndex()).ToString(); 
    }

When items are added or removed from the source list then the numbers can get out of sync for a while

When items are added or removed from the source list then the numbers can get out of sync for a while.For a fix to this, see the attached behavior here:

<DataGrid ItemsSource="{Binding ...}"
          behaviors:DataGridBehavior.DisplayRowNumber="True">

use this instead if you want to count from 1

void DataGrid_LoadingRow(object sender, DataGridRowEventArgs e)
{
    e.Row.Header = (e.Row.GetIndex()+1).ToString(); 
}

Hope this helps

Community
  • 1
  • 1
Frebin Francis
  • 1,905
  • 1
  • 11
  • 19