I have a data bound listbox in a WPF control. All I want is the text of the selected index. If I use SelectedItem.ToString I get the key and text. If I use SelectedValue.ToString I get just the key.
A few forums have suggested casting like below but that doesn't seem to be working.
InputName nameInput = new InputName((ListBoxItem)LbContractors.SelectedItem.ToString()));
This is how I am binding the control. Is that messing it up.
LbContractors.ItemsSource = myDictionary;
LbContractors.SelectedValuePath = "Key";
LbContractors.DisplayMemberPath = "Value";
答案 0 :(得分:5)
This should do the trick.
(LbContractors.SelectedItem as ListBoxItem).Content.ToString();
UPDATE
Or try to do this. Convert to Nullable KeyValuePair and get the Value.
var kvp = (KeyValuePair<string, object>?) LbContractors.SelectedItem);
if(kvp != null && kvp.Value != null) {
string selectedText = kvp.Value.ToString();
}
In one line with null checking :)
string selectedText = ((KeyValuePair<string, object>?) LbContractors.SelectedItem)?.Value?.ToString();
答案 1 :(得分:0)
为什么我不能像在winform中那样简单地抓取文本
如果对象被正确取消引用,就可以了....
我想要的只是所选索引的文本。
但是,根据您的示例,键值对结构的ToString()
文本应该返回什么?你有ToString()
超载吗?
要解决的两个问题
ToString()
和引用 Key
或Value
的相应属性。 否则这里有例子。第一个是绑定到字典的列表框
myDictionary = new Dictionary<string, string>()
{
{"Alpha", "The First Letter"},
{"Beta", "The Second Letter"},
{"Omega", "Omega Letter"},
};
当用户选择每个项目时,键和值将显示在列表框下方的文本框中:
<强>的Xaml 强>
<ListBox Name="lbDictionary"
ItemsSource="{Binding myDictionary}"
SelectedValuePath="Key"
DisplayMemberPath="Value"/>
在文本框中访问它们(我没有为了简洁而显示“Key”和“Value”的标签)
<TextBlock Text="{Binding SelectedItem.Key, ElementName=lbDictionary}"/>
...
<TextBlock Text="{Binding SelectedItem.Value, ElementName=lbDictionary}"/>
因此,Key
背后的代码访问权限是这样的,Value
将是相同的:
if (lbDictionary.SelectedItem != null)
MessageBox.Show(((KeyValuePair<string, string>) (lbDictionary.SelectedItem)).Key);
else
MessageBox.Show("Select something");
答案 2 :(得分:-1)
Why not use LblContractors.Text;
if that's all you're looking for?