如何从WPF中的ComboBox获取文本值?

这可能是C#101所涵盖的内容,但我无法在谷歌或堆栈溢出的任何地方找到这个问题的易于理解的答案。 有没有更好的方法从combobox中返回文本值而不使用我想出的这种糟糕的工作?

private void test_site_SelectionChanged(object sender, SelectionChangedEventArgs e) { string cmbvalue = ""; cmbvalue = this.test_site.SelectedValue.ToString(); string[] cmbvalues = cmbvalue.Split(new char[] { ' ' }); MessageBox.Show(cmbvalues[1]); } 

请不要强硬我,我现在真的只是拿起c#和OOP。

看起来你的ComboBox中有ComboBoxItems,因此SelectedValue返回一个ComboBoxItem,因此ToString返回类似ComboBox SomeValue东西。

如果是这种情况,您可以使用ComboBoxItem.Content获取内容:

 ComboBoxItem selectedItem = (ComboBoxItem)(test_site.SelectedValue); string value = (string)(selectedItem.Content); 

但是,更好的方法是将ComboBox.ItemsSource设置为所需的字符串集合,而不是使用ComboBoxItems的集合填充ComboBox:

 test_site.ItemsSource = new string[] { "Alice", "Bob", "Carol" }; 

然后SelectedItem将直接为您提供当前选定的字符串。

 string selectedItem = (string)(test_site.SelectedItem); 

在加载事件放

 DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(ComboBox.TextProperty, typeof(ComboBox)); dpd.AddValueChanged(cmbChungChi, OnTextChanged); 

并通过function获取文本

 private void OnTextChanged(object sender, EventArgs args) { txtName.Text = cmbChungChi.Text; } 

祝好运。