I have a listbox with one item on it, it can then get replaced by several items (words) taken from the text inputted in a textbox. They're added with listbox.Items.Add(word)
.
I want to be able to convert those words from the listbox back into strings as they are selected (so I can do other stuff with them) but I have encountered two problems that I'm not sure how to deal with:
- When the original item is selected I get an exception:
System.NullReferenceException: 'Object reference not set to an instance of an object.'
when using string s = ((ListBoxItem)listbox.SelectedItem).Content.ToString();
and
"System.NullReferenceException: 'Object reference not set to an instance of an object.'
System.Windows.Controls.Primitives.Selector.SelectedValue.get returned null."
when using string s = listbox.SelectedValue.ToString();
- When any of the new items are selected nothing happens. I assume this is because the event handler is only attached to the single item that's on the list in the beginning, but I am not sure how to apply it to items that aren't there yet. Is there an event handler for when any item from a listbox is selected?
Any help would be appreciated, thank you in advance.