How Do You Get The Currently Selected Rows In A WPF Datagrid

Mar 19, 2009 at 6:56 PM
Okay so oddly enough there is no MyDataGrid.Rows property or any other way that I can find to get to the rows in a WPF datagrid.  So I resulted to traversing the visual tree to find the DataGridRows so that I could determine which rows are selected and record the selected indexes.  This seems to work pretty well.  However, for some odd reason it doesn't return all of the rows?  I have 9 rows in my datagrid.  When I run the code below, it only hits the break point 5 times(every other row).  Any help would be greatly appreciated.

Jason 

 FindSelectedRows(0, MyDatagrid)

    Private Sub SelectRows(ByVal depth As Integer, ByVal obj As Object)

         If (TypeOf obj Is Microsoft.Windows.Controls.DataGridRow) Then
              'Perform logic to record index.
        End If

            For i As Integer = 0 To VisualTreeHelper.GetChildrenCount(obj) - 1
                FindSelectedRows(depth + 1, VisualTreeHelper.GetChild(obj, i))
                i = i + 1
            Next

    End Sub ' End  FindSelectedRows
Mar 20, 2009 at 8:42 AM
How about something like this? (Untested/pseudo) C# because C# is what I am accustomed to, but should be easy to translate to VB.NET.

int n = 0; // number of selected rows found
int selectedIndexes[dataGrid.SelectedItems.Count]; // 0-based array
foreach (object item in dataGrid.SelectedItems)
{
    selectedIndexes[n] = dataGrid.Items.IndexOf(item); // find this
    n = n + 1;
}

The code above might not be terribly efficient with large numbers of items and selected items, but it should certainly be a lot better than traversing the visual tree just to get the indexes for the currently selected rows.
Mar 20, 2009 at 2:09 PM
Awesome thank you very much!  That worked.  I had one more question for you.  I want to rebind my datagrid and then after the fact reselect certain rows.  How do you reselect rows in a WPF datagrid. 

Any help would be greatly appreciated.

Jason