SelectedItem and SelectedIndex when SelectionUnit=Cell

Mar 10, 2009 at 10:53 AM

If i set SelectionUnit=FullRow, i can access SelectedItem and SelectedIndex.
If i set SelectionUnit=Cell, then SelectedIndex is always -1, and SelectedItem is null.

I can acces SelectedItem with DataGrid.SelectedCells[0].Item but :
 - the CurrentItem of my CollectionView is null
 - when i change the CurrentItem of my CollectionView, the SelectedCells don't change
Thank you in advance
Mar 24, 2009 at 7:44 PM
I'm relatively new to WPF so I'm not sure why the SelectedItem is null in this case.  But I have a workaround - if you implement the SelectedCellsChanged event you can look at the SelectedCellsChangedEventArgs that are passed in as the selected cells change.  This object contains a "SelectedCells" collection - just grab the first one and look at its Item property -- that is the underlying SelectedItem.  Then you can assign this item to a local property so you can retrieve it from outside the event handler.

private MyBusinessObjecType _ItemICanAccessInMyClass; //for best use, make MyBusinessObjectType implement INotifyPropertyChanged

private void dg_SelectedCellsChanged(object sender, Microsoft.Windows.Controls.SelectedCellsChangedEventArgs e)
                if (dg.SelectedCells!=null && dg.SelectedCells.Count > 0)
                    Microsoft.Windows.Controls.DataGridCellInfo cellinfo = dgAddedUsers.SelectedCells[0];
                    _ItemICanAccessInMyClass = cellinfo.Item as MyBusinessObjectType;

All that said, it is better when possible to avoid using the SelectedIndex, and if you need to keep track of activity on a certain row (say, which rows have a checkbox selected), bind the data  in each cell to a property of the underlying business object instead of doing it the "old school" based on row index.
Mar 24, 2009 at 8:34 PM
In DataGrid's selection model, each row corresponds to an item in your Items collection / ItemsSource. So, in order to select an item (i.e. SelectedItem), you need to be in a mode where rows are selectable. SelectionUnit can be set to either FullRow or CellOrRowHeader. CurrentItem is tied to SelectedItem.