ComboBox SelectedItem未显示其值

时间:2011-06-12 11:38:35

标签: c# wpf combobox

我有一个ComboBox,其ComboBoxItem都是在运行时生成的(以编程方式)。只要有ComboBox.SelectionChange,程序就会显示MessageBox,显示ComboBox的所选内容

private void cb2_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    MessageBox.Show(cb2.SelectedItem.ToString());
}

然而,它告诉我:

System.Windows.Controls.ComboBoxItem:Hello World

我只想展示“Hello World”而不是“System ....”。我尝试了SelectedValue,这也显示了同样的事情。

2 个答案:

答案 0 :(得分:2)

您需要将所选项目转换为ComboBoxItem并仅获取其内容。

MessageBox.Show((cb2.SelectedItem as ComboBoxItem).Content.ToString());

答案 1 :(得分:2)

您应该考虑使用绑定而不是事件处理程序。这样可以使代码更清晰,并且可以更好地分离表示和流程之间的关注点:

按如下方式声明您的组合:

<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;
    }
}

Combo的SelectedValue属性上的绑定表达式将导致SelectedCountry上的属性设置器在组合中所选项目发生更改时触发。

public class Country
{
    public int Id { get; set;}

    public string Name {get; set;}
}