我在WPF控件中有一个数据绑定列表框.我想要的只是所选索引的文本.如果我使用SelectedItem.ToString,我会得到密钥和文本.如果我使用SelectedValue.ToString我只得到密钥.
一些论坛建议如下所示,但这似乎没有用.
InputName nameInput = new InputName((ListBoxItem)LbContractors.SelectedItem.ToString()));
Run Code Online (Sandbox Code Playgroud)
这就是我绑定控件的方式.这搞砸了吗?
LbContractors.ItemsSource = myDictionary;
LbContractors.SelectedValuePath = "Key";
LbContractors.DisplayMemberPath = "Value";
Run Code Online (Sandbox Code Playgroud)
这应该可以解决问题.
(LbContractors.SelectedItem as ListBoxItem).Content.ToString();
Run Code Online (Sandbox Code Playgroud)
UPDATE
或者尝试这样做.转换为Nullable KeyValuePair并获取Value.
var kvp = (KeyValuePair<string, object>?) LbContractors.SelectedItem);
if(kvp != null && kvp.Value != null) {
string selectedText = kvp.Value.ToString();
}
Run Code Online (Sandbox Code Playgroud)
在一行中进行空检查:)
string selectedText = ((KeyValuePair<string, object>?) LbContractors.SelectedItem)?.Value?.ToString();
Run Code Online (Sandbox Code Playgroud)