[英]How to get value of SelectedValue in ComboBox filled with Dictionary
We have dictionary like this:我们有这样的字典:
var dictionary = new Dictionary<int, int> { { 0, 100 }, { 1, 202 }, { 2, 309 }, };
and so on a lot of values.等等很多值。 dictionary binded to comboBox like this:
像这样绑定到组合框的字典:
comboBox1.ItemsSource = dictionary;
comboBox1.DisplayMemberPath = "Value";
I'm wonder how can I get selectedvalue of this comboBox, if comboBox.Text works only for manually inputted values and this code:我想知道如何获得此组合框的 selectedvalue,如果组合框.文本仅适用于手动输入的值和此代码:
string value = comboBox1.SelectedValue.ToString();
return value like [1, 202], while I need clear int TValue "202".返回值如 [1, 202],而我需要清除 int TValue "202"。 I'm unable to find similar question so I ask it there and hope that the answer may be useful for someone else.
我找不到类似的问题,所以我在那里问,希望答案对其他人有用。
Looks like you have to cast SelectedValue
into KeyValuePair<int, int>
:看起来您必须将
SelectedValue
转换为KeyValuePair<int, int>
:
string value = ((KeyValuePair<int, int>)comboBox1.SelectedValue).Value.ToString();
However, you should put a brakepoint there and check what type SelectedValue
really is.但是,您应该在那里放置一个刹车点并检查
SelectedValue
到底是什么类型。
I assume it's KeyValuePair<int, int>
because your source collection is Dictionary<int, int>
and because of output string for SelectedValue.ToString()
which is [1, 202]
.我假设它是
KeyValuePair<int, int>
因为你的源集合是Dictionary<int, int>
并且因为SelectedValue.ToString()
的输出字符串是[1, 202]
。
If you specify the ValueMember, you can avoid the cast operation.如果指定 ValueMember,则可以避免强制转换操作。 It's important that you set the path before the datasource, or it will fire the changed event with a selected value that is a keyvaluepair.
在数据源之前设置路径很重要,否则它将使用作为键值对的选定值触发更改的事件。
comboBox1.DisplayMemberPath = "Value";
comboBox1.SelectedValuePath= "Key";
comboBox1.ItemsSource = dictionary;
string value = comboBox1.SelectedValue.ToString();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.