ListBox.SelectedItem拒绝设置

时间:2013-04-03 14:38:53

标签: 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) 
        throw new ApplicationException("WTF?");
}

在任何时候都没有引发ListBox.SelectionChanged事件。

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

1 个答案:

答案 0 :(得分:0)

您需要使用SetSelected方法,如下所示:

MyListBox.SetSelected(index, true);

或将其设置在项目本身上,如下所示:

MyListBox.Items(index).Selected = true;

我不确定你问题中的newItem是什么,所以你需要在列表中标识它的索引并将其放在上面代码段中我index的位置。

相关问题