如何在ComboBox中使用Dictionary填充SelectedValue的值

Mik*_*ike 7 c# combobox dictionary

我们有这样的字典:

var dictionary = new Dictionary<int, int> { { 0, 100 }, { 1, 202 }, { 2, 309 }, };
Run Code Online (Sandbox Code Playgroud)

等等很多价值观.字典绑定到comboBox,如下所示:

comboBox1.ItemsSource = dictionary;
comboBox1.DisplayMemberPath = "Value";
Run Code Online (Sandbox Code Playgroud)

我想知道如果comboBox.Text仅适用于手动输入的值和此代码,我如何获得此comboBox的selectedvalue:

string value = comboBox1.SelectedValue.ToString();
Run Code Online (Sandbox Code Playgroud)

返回值如[1,202],而我需要明确的int TValue"202".我无法找到类似的问题所以我在那里问它并希望答案可能对其他人有用.

Mar*_*zek 9

看起来你必须SelectedValue投入KeyValuePair<int, int>:

string value = ((KeyValuePair<int, int>)comboBox1.SelectedValue).Value.ToString();
Run Code Online (Sandbox Code Playgroud)

但是,你应该在那里放一个刹车点,检查一下SelectedValue是什么类型的.

我认为这是KeyValuePair<int, int>因为你的源集合是Dictionary<int, int>因为输出字符串SelectedValue.ToString()[1, 202].