I want to realize a general and simple function: in a combox, get the selected item text through user selection in a WPF ComboBox, but I could not find a way to do it even after search internet. Unbelievable. Hope anyone can help me.
the XAML and c# code are as follows. I have given the comments and my question as well the code. Note that I have tried the similar functions in both MainWindow() and Selectionchanged event. The problem occurs only in the latter function. But I need get the selected item, e.g. "item1" when I select the combox item to be the first item. But it gives an error (See below) when starting the debugging.
strangly, the XAML code can not be fully copied to here. however, you should assume the xaml code has no any problem. it is not complete only due to the editor here.
<ComboBox x:Name=
"
ComBoxTest"
Height=
"
50"
SelectionChanged=
"
ComBoxTest_SelectionChanged"
SelectedValuePath=
"
Content"
>
<ComboBoxItem IsSelected=
"
True"
>item1
</
ComboBoxItem
>
<ComboBoxItem>item2
</
ComboBoxItem
>
</
ComboBox
>
namespace
WPFComboBoxTest
public
partial
class
MainWindow : Window
public
MainWindow()
InitializeComponent();
MessageBox.Show(ComBoxTest.SelectedItem.ToString());
MessageBox.Show(ComBoxTest.SelectedValue.ToString());
string
text = ((ComboBoxItem)ComBoxTest.SelectedItem).Content.ToString();
MessageBox.Show(text);
private
void
ComBoxTest_SelectionChanged(
object
sender, SelectionChangedEventArgs e)
MessageBox.Show(ComBoxTest.SelectedItem.ToString());
MessageBox.Show(ComBoxTest.SelectedValue.ToString());
string
text = ((ComboBoxItem)ComBoxTest.SelectedItem).Content.ToString();
MessageBox.Show(text);
What I have tried:
tried different ways, selecteditem, selectedvalue, items, none works.
search also internet, but it is not successful.
Read the question carefully.
Understand that English isn't everyone's first language so be lenient of bad
spelling and grammar.
If a question is poorly phrased then either ask for clarification, ignore it, or
edit the question
and fix the problem. Insults are not welcome.
Don't tell someone to read the manual. Chances are they have and don't get it.
Provide an answer or move on to the next question.
Let's work to help developers, not make them feel stupid.