2015-07-20 124 views
2

我正在處理一個C#wpf應用程序,其中有一個列表框,並且我想獲取在發生更改之前選擇的元素的值ListBox SelectionChanged事件:獲取它被更改之前的值

我成功地得到了新的價值是這樣的:

<ListBox SelectionChanged="listBox1_SelectedIndexChanged"... /> 

private void listBox1_SelectedIndexChanged(object sender, EventArgs e) 
    { 
     test.add(listBox1.SelectedItem.ToString()); 
    } 

但我需要這樣的東西listBox1.UnselectedItem獲得這一變化過程中是未選中的元素。任何想法 ?

+0

該值應該在事件參數中。 – Taekahn

+0

@Taekahn如果你知道一個簡單的方法來從'EventArgs'獲取值,那麼我會推薦發佈一個答案 – ean5533

+0

[MSDN](https://msdn.microsoft.com/en-us/library/system.windows。 controls.selectionchangedeventargs(v = vs.110).aspx)來拯救。 –

回答

5

SelectionChangedEventArgs有一個名爲RemovedItems屬性,它包含了新的被拆除的項目清單選擇。您可以用SelectionChangedEventArgs代替EventArgs並訪問參數的屬性(Casting也可以,因爲它是一個子類)。

private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     List<string> oldItemNames = new List<string>(); 
     foreach(var item in e.RemovedItems) 
     { 
      oldItemNames.Add(item.ToString()); 
     } 
    } 
+0

它的作品,它很漂亮!非常感謝 ! –

2

一個簡單的方法是有一個private int _selectedIndex從SelectedIndex屬性存儲的值,例如:

private int _selectedIndex; 

private void listBox1_SelectedIndexChanged(object sender, EventArgs e) 
{ 
    test.add(listBox1.SelectedItem.ToString()); 

    // grab the _selectedIndex value before we update it. 
    var oldValue = _selectedIndex; 
    _selectedIndex = listBox1.SelectedIndex; 

    // code utilizing old and new values 
    // oldValue stores the index from the previous selection 
    // _selectedIndex has the value from the current selection 
} 
+0

好吧,我想我可以自己想想!謝謝你寫下整件事:-) –

+0

很好的答案。你實際上引發了我對這件事的興趣。 – Adam

相關問題