Get the text of the selected item in a WPF listbox

时间:2016-04-04 16:48:49

标签: c# wpf listbox

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";

3 个答案:

答案 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()超载吗?

要解决的两个问题

  1. 您确定SelectedItem不为空吗?在访问之前检查该条件。
  2. 应该转换为适当的结构(KVP),而不是盲目地调用ToString()引用 KeyValue的相应属性。
  3. 否则这里有例子。第一个是绑定到字典的列表框

    myDictionary = new Dictionary<string, string>()
                    {
                        {"Alpha", "The First Letter"},
                        {"Beta", "The Second Letter"},
                        {"Omega", "Omega Letter"},
                    };
    

    当用户选择每个项目时,键和值将显示在列表框下方的文本框中:

    enter image description here

    <强>的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?