Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the text of the selected item in a WPF listbox

Tags:

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";
like image 923
Jeebwise Avatar asked Oct 22 '25 20:10

Jeebwise


1 Answers

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();
like image 193
kent-id Avatar answered Oct 24 '25 13:10

kent-id