【发布时间】:2011-04-04 19:03:12
【问题描述】:
我在 WPF 中有一个列表框,它使用 ItemSource 属性绑定到 ObservableCollection。这工作正常,显示正确的项目。
列表框(包含图像名称列表)在 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 处理程序进行某种检查?
【问题讨论】:
标签: c# wpf event-handling