ComboBox SelectedItem未显示其值

问题描述

| 我有一个
ComboBox
,它的
ComboBoxItem
都是在运行时生成的(以编程方式)。每当出现“ 2”时,程序将显示“ 3”,其中显示了“ 0”的选定内容
private void cb2_SelectionChanged(object sender,SelectionChangedEventArgs e)
{
    MessageBox.Show(cb2.SelectedItem.ToString());
}
但是,它显示给我: System.Windows.Controls.ComboBoxItem:Hello World 我只想显示“ Hello World”,而不是“ System .... \”。我尝试了SelectedValue,并且也显示了相同的内容。     

解决方法

        您需要将选定的项目强制转换为ComboBoxItem并仅获取其内容。
MessageBox.Show((cb2.SelectedItem as ComboBoxItem).Content.ToString());
    ,        您应该考虑使用绑定而不是事件处理程序。这样可以使代码更简洁,并且表示和流程之间的关注点更加分离: 声明您的组合,如下所示:
<ComboBox x:Name=\"cboCountries\" DisplayMemberPath=\"Name\" SelectedItem=\"{Binding SelectedCountry}\" ItemsSource=\"{Binding Countries}\" />
然后,将ComboBox绑定到Window上的集合(最好是ViewModel):
public Window1()
{
    InitializeComponent();

    DataContext = this;

    this.Countries = new ObservableCollection<Country>();
    this.Countries.Add(new Country {Id = 1,Name = \"United Kingdom\" });
    this.Countries.Add(new Country {Id = 1,Name = \"United States\" });
}

public ObservableCollection<Country> Countries {get; set;}

private Country selectedCountry;

public Country SelectedCountry
{
    get { return this.selectedCountry; }
    set 
    {
        System.Diagnostics.Debug.WriteLine(string.Format(\"Selection Changed {0}\",value.Name));
        this.selectedCountry = value;
    }
}
组合中的SelectedValue属性上的绑定表达式将使SelectedCountry上的属性设置器在组合中更改所选项目时触发。
public class Country
{
    public int Id { get; set;}

    public string Name {get; set;}
}
    

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...