0

I have a DataGrid (named OperatorDataGrid) and the row number is set via the LoadingRow event:

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

And the DataGrid itself is bound to an ObservableCollection<FilterRow> where FilterRow as a property called Index (not currently being used). The binding is done in the user control's constructor:

public AdvancedFilter()
{
    InitializeComponent();
    SetDefaults();

    FilterRows.Add(new FilterRow());
    OperatorDataGrid.ItemsSource = FilterRows;
}

What I can't figure out is how to bind the Row.Header value back to the model as items can constantly be added/removed. The LoadingRow method handles showing the number in the DataGrid but I can't get that value back into the object bound to that specific row since the header is not a specific column that is defined in the <DataGrid.Columns> section in the XAML. I did try the solution found here, however whenever I added a new row, the header cell would show Index is 0 for every row. Any suggestions would be appreciated.

Dominick
  • 322
  • 1
  • 3
  • 16
  • Keep in mind, a single call to the GetIndex () method does not guarantee that the correct index will be set for the entire lifetime of the element. If elements are deleted or inserted in the collection, then this method must be called again for all lines from the changed element to the end of the collection. You will also get problems when applying different sorting in the DataGrid. In general, the assignment of indices is best done in the VM, and in the DataGrid it is to bindin to this property. – EldHasp Apr 19 '21 at 18:06

1 Answers1

1

You could simply set the source property yourself when you set the Header:

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

    var dataObject = e.Row.DataContext as YourClass;
    if (dataObject != null)
        dataObject.RowNumber = rowNumber;
}

Then you know that the row number that you see in the view is synchronized with the property of the data object.

There is no way to bind directly to a method like GetIndex() in XAML which is why you handle the LoadingRow event in the first place.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • I tried to figure out the indexing of strings (you need to look for that topic) and, as far as I remember, this method does not guarantee correct operation in all cases. Problems arise when inserting and removing items from the source collection, and when using sorting in the DataGrid. – EldHasp Apr 19 '21 at 17:58
  • @EldHasp Luckily for my use, sorting won't be available and only one item can be removed at a time and it is always the last item. – Dominick Apr 20 '21 at 13:57
  • @mm8 I think this is exactly what I need. Thank you, I will try it out. – Dominick Apr 20 '21 at 13:59