2013-03-22 130 views
6

我們的字典是這樣的:如何獲得的SelectedValue的價值組合框充滿字典

var dictionary = new Dictionary<int, int> { { 0, 100 }, { 1, 202 }, { 2, 309 }, }; 

等很多價值觀。字典綁定到組合框是這樣的:

comboBox1.ItemsSource = dictionary; 
comboBox1.DisplayMemberPath = "Value"; 

我不知道如何可以得到這個組合框的SelectedValue,如果comboBox.Text僅適用於手動輸入值,並驗證碼:

string value = comboBox1.SelectedValue.ToString(); 

返回值像[1,202],而我需要明確的int TValue「202」。我無法找到類似的問題,所以我在那裏問它,並希望答案可能對其他人有用。

+0

使用此替代方法學習如何使用「字典或字典」創建'BindingSource'' http://stackoverflow.com/questions/6412739/binding-combobox-using-dictionary-as-the- datasource – MethodMan 2013-03-22 21:16:23

回答

8

看起來你要投SelectedValueKeyValuePair<int, int>

string value = ((KeyValuePair<int, int>)comboBox1.SelectedValue).Value.ToString(); 

但是,你應該把一個brakepoint那裏檢查一下是什麼類型SelectedValue真的是。

我認爲這是KeyValuePair<int, int>,因爲您的源收集是Dictionary<int, int>,並且因爲SelectedValue.ToString()的輸出字符串,即[1, 202]

+0

輝煌!非常棒,非常感謝你!我會盡快接受你的回答。 – Mike 2013-03-22 21:17:17

+0

謝謝這是什麼需要.... – Armaan 2015-12-12 08:38:24