Tomtom
Tomtom

Reputation: 9394

Show row-number in DataGrid

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?

Upvotes: 0

Views: 6641

Answers (1)

Frebin Francis
Frebin Francis

Reputation: 1915

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

Upvotes: 1

Related Questions