【问题标题】:How do i get the text value from a ComboBox in WPF?如何从 WPF 中的 ComboBox 获取文本值?
【发布时间】:2015-05-12 00:52:51
【问题描述】:

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

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。

【问题讨论】:

    标签: c# wpf combobox


    【解决方案1】:

    看起来您的 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);
    

    【讨论】:

    • 第一个建议通过异常:无法将“System.Windows.Controls.ListBoxItem”类型的对象转换为“System.Windows.Controls.ComboBoxItem”类型。
    【解决方案2】:

    加载事件放置

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

    并通过函数获取文本

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

    祝你好运。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-09-26
      • 1970-01-01
      • 1970-01-01
      • 2021-03-31
      • 2019-02-08
      • 2019-07-09
      相关资源
      最近更新 更多