Dominick
Dominick

Reputation: 476

Binding DataGrid Row Number to Property

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.

Upvotes: 0

Views: 725

Answers (1)

mm8
mm8

Reputation: 169420

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.

Upvotes: 1

Related Questions