C# 如何从WPF中的组合框中获取文本值?

C# 如何从WPF中的组合框中获取文本值?,c#,wpf,combobox,C#,Wpf,Combobox,这可能是C#101中的一些内容,但我在google或stack overflow的任何地方都找不到一个容易理解的答案。有没有更好的方法从组合框中返回文本值,而不使用我提出的这种蹩脚的解决方法 private void test_site_SelectionChanged(object sender, SelectionChangedEventArgs e) { string cmbvalue = ""; cmbvalue = this.test_site.SelectedVal

这可能是C#101中的一些内容,但我在google或stack overflow的任何地方都找不到一个容易理解的答案。有没有更好的方法从组合框中返回文本值,而不使用我提出的这种蹩脚的解决方法

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返回ComboxItem,而ToString则返回类似于
ComboboxSomeValue
的内容

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

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);
并通过函数获取文本

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

祝您好运。

第一个建议通过异常:无法将类型为“System.Windows.Controls.ListBoxItem”的对象强制转换为类型为“System.Windows.Controls.ComboxItem”。