WPF Deleting item from listbox
I have a listbox in WPF that's bound to a ObservableCollection using the ItemSource property. This works fine, the correct items are shown.
The listbox (which contains a list of image names) has an event handler on the Selec开发者_运维技巧tionChanged event which updates the source of an Image control with the path to the selected image (effectively giving an image preview).
I have the following code to remove an item from the lisbox, on a button's click event:
if (lstLocal.SelectedIndex > -1)
{
localImages.RemoveAt(lstLocal.SelectedIndex);
}
localImages being the ObservableCollection
and lstLocal being the ListBox
.
However, when I remove the selected item this causes the SelectionChanged event to fire. My SelectionChanged event handler makes use of the SelectedIndex property on the listbox. I get the exeption Index was out of range. Must be non-negative and less than the size of the collection.
, so I'm guessing that removing an item causes SelectedIndex to be set to something like null (or a negative number)?
Is there a way around this problem? I'm guessing there's a better way for me to remove items, or I need some sort of check on my SelectionChanged handler?
Wrap the code in your SelectionChanged handler in a
if (lstLocal.SelectedItem != null)
{
...
}
Ah, a classic annoyance of the ListBox control. When altering the bound collection, it can clear the selection and reset the scroll position to the top. It's truly irritating when you have to select items from a list and edit them piecemeal as part of a workflow.
You may want to maintain a "currently selected item" object reference when changing the list so that you can keep the selection if something changes behind the scenes. Then you can also make sure that if it exists, that it stays in view by scrolling back to that item using the ScrollIntoView method.
A SelectedIndex of -1 means nothing is selected, as you have already remembered. This is an ancient hold-over from pre-.NET, before the SelectedItem property existed. Nowadays SelectedItem will be null at the same time as SelectedIndex is -1.
精彩评论