C# ListBox.SelectedItem拒绝设置

C# ListBox.SelectedItem拒绝设置,c#,wpf,listbox,selecteditem,C#,Wpf,Listbox,Selecteditem,以下代码中引发异常的可能原因是什么 var oldItem = this.MyListBox.SelectedItem; if (this.MyListBox.Items.Contains(newItem)) { this.MyListBox.SelectedItem = newItem; if (this.MyListBox.SelectedItem != newItem && this.MyListBox.SelectedItem == oldItem)

以下代码中引发异常的可能原因是什么

var oldItem = this.MyListBox.SelectedItem;

if (this.MyListBox.Items.Contains(newItem))
{
    this.MyListBox.SelectedItem = newItem;

    if (this.MyListBox.SelectedItem != newItem && this.MyListBox.SelectedItem == oldItem) 
        throw new ApplicationException("WTF?");
}
任何时候都不会引发ListBox.SelectionChanged事件


编辑:oldItem和newItem是相同类型的简单业务对象。它们不是空的。

您需要使用如下方法之一:

MyListBox.SetSelected(index, true);
或者将其设置在项目本身上,如下所示:

MyListBox.Items(index).Selected = true;

我不确定你的问题中有什么
newItem
,因此,您需要在列表中确定它的索引,并将其放在上面代码段中我的
索引中。

@Matt您的新项目是什么-您如何启动它?在哪里执行?多线程是最明显的猜测-其他线程在您的线程通过条件时修改所选项目您询问什么您的代码可能会抛出该异常,对吗?我的第一个猜测是:您的集合上有一个筛选器视图,您试图将所选项目设置为筛选时删除的对象。您是否使用断点查看了将newItem设置为selecteditem时newItem的值?您是否使用了断点来查看该行之后发生了什么?