我在WPF中有一个绑定到使用ItemSource属性的ObservableCollection的列表框。这工作正常,显示正确的项目。WPF从列表框中删除项目
列表框(包含图像名称列表)在SelectionChanged事件上有一个事件处理程序,该事件处理程序使用所选图像的路径(有效地给出图像预览)更新Image控件的来源。
我有以下代码从lisbox删除一个项目,一个按钮的点击事件:
if (lstLocal.SelectedIndex > -1)
{
localImages.RemoveAt(lstLocal.SelectedIndex);
}
localImages作为ObservableCollection
和lstLocal作为ListBox
。
但是,当我删除所选项目时,会导致SelectionChanged事件触发。我的SelectionChanged事件处理程序利用列表框上的SelectedIndex属性。我得到豁免Index was out of range. Must be non-negative and less than the size of the collection.
,所以我猜测删除一个项目导致SelectedIndex被设置为类似null(或负数)?
有没有办法解决这个问题?我猜有更好的方法来移除项目,或者我需要对我的SelectionChanged处理程序进行某种检查?
谢谢。想想我在那里有一段健忘的时刻! – AndrewC 2011-04-04 19:13:23