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 /// < summary > /// Interaction logic for MainWindow.xaml /// < /summary > public partial class MainWindow : Window public MainWindow() InitializeComponent(); MessageBox.Show(ComBoxTest.SelectedItem.ToString()); // System.Windows.Controls.ComboxItem:item1 MessageBox.Show(ComBoxTest.SelectedValue.ToString()); // item1 (OK) string text = ((ComboBoxItem)ComBoxTest.SelectedItem).Content.ToString(); // item1 (Ok, too) MessageBox.Show(text); private void ComBoxTest_SelectionChanged( object sender, SelectionChangedEventArgs e) MessageBox.Show(ComBoxTest.SelectedItem.ToString()); // System.Windows.Controls.ComboxItem, only, after starting the programm, no item1, which is selected by default i XAML code. But after starting programm, it shows System.Windows.Controls.ComboxItem:item1 when I select the first item MessageBox.Show(ComBoxTest.SelectedValue.ToString()); // problem, when start debugging: an unhandled exception of teyp 'System.Refection.TragetInvocationException' occured. I think this will work if I really hit the ComboBox and select one item. But I have no chance since this error occurs once starting the programm. string text = ((ComboBoxItem)ComBoxTest.SelectedItem).Content.ToString(); // same problem MessageBox.Show(text); // my question: how to deal with this problem? 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.
  •