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";
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();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With