Sakuya
Sakuya

Reputation: 680

Get DataGrid row index of value?

What I'm trying to do is get the row index from content.

I have a DataGrid with 2 columns, one for an Identifier (as DataGridTextColumn) and another for Refferer that refers to specific identifiers (as DataGridTemplateColumn label, it has a MouseUp handler and conditional formatting).

I also have a CollectionViewSource with source as a List which contains the identifiers and referrers.

When an item from the referrers column is clicked, the MouseUp handler retrieves the content of the label, like so:

private void Item_MouseUp(object sender, RoutedEventArgs e) {
    string _Referrer = (string)(sender as Label).Content;
    //Something here to get index of row that contains _Referrer.
    e.Handled = true;
}

I have tried naming my DataGrid and doing `dataGrid.Items.IndexOf(_Referrer) but this doesn't produce the index of the item.

My intention for retrieving this row index is so that I can have the list scrolled to the specific item using:

dataGrid.SelectedIndex = IndexOfIdentifier;
dataGrid.UpdateLayout();
dataGrid.ScrollIntoView(dataGrid.SelectedItem);

Upvotes: 0

Views: 2155

Answers (1)

keymusicman
keymusicman

Reputation: 1291

Try the following thing:

var selectedItem = dataGrid.Items.OfType<People>().FirstOrDefault(q => q.Referrer = _Referrer);
if (selectedItem != null)
{
    // you can get index of this item if you want:
    // var selectedItemIndex = dataGrid.Items.IndexOf(selectedItem);

    dataGrid.SelectedItem = selectedItem;
}

Upvotes: 1

Related Questions