I have a DataGrid a user can add items to by entering data in the last row. I also have a button that deletes the currently selected item. But when the last (empty, for adding new items) row is selected, whatever was the last selected item remains in SelectedItem. So if I open the window, select the last row, and press the delete button, it will delete the first row, as it is selected by default, and selecting the last row did not change SelectedItem. Any good way to deal with this?
To clarify:
SelectedItem="{Binding X}"
X in the ViewModel does not change when the last row is selected (the setter isn't invoked at all). I'm not sure whether the SelectedItem property itself changes, but I would assume it doesn't.
There is also an exception when I select the last row (red border), but when I click it again to start entering data, the red border disappers. Not sure if these two are related.
Best Answer
Run the following example and you'll see why it doesn't work.
XAML:
Code-behind:
As you can see when running, selecting the "new" row causes a sentinel value to be set as the selected item in the
DataGrid
. However, WPF is unable to convert that sentinel item to aPerson
, so theSelectedItem
binding fails to convert.To fix this, you could put a converter on your binding that detects the sentinel and returns
null
when detected. Here's a converter that does so:As you can see, it is an unfortunate necessity to test against the
ToString()
value of the sentinel, because it is an internal type. You could alternatively (or in addition) check thatGetType().Name
isNamedObject
.