在WPF中获取ComboBox中的属性值

时间:2017-01-12 03:59:30

标签: c# wpf

我有一个comboBox,它被绑定到列表(来自数据库,使用实体框架)。我想在comboBox的AdId上获得所选项目(对象)的SelectionChanged

public class Ad
{          
    public int AdId { get; set; }
    public string AdContent { get; set; }
}

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox cmd = (ComboBox) sender;
    int AdId = cmd.SelectedItem;

    ???????????? I'm stuck here how to get AdId from SelectedItem... tried SelectedValue and SelectedValuePath... didn't work
}

2 个答案:

答案 0 :(得分:3)

ComboBox的cmd.SelectedItem属性将返回一个对象,您可以将它们转换为您自己的业务对象。然后您可以轻松访问其属性,如下所示:

int AdId = ((Ad)cmd.SelectedItem).AdId ;
string AdContent =  ((Ad)cmd.SelectedItem).AdContent; 

答案 1 :(得分:3)

设置SelectedValuePath="AdId"

从代码中获取选定的值,如下所示

private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    ComboBox cmd = (ComboBox) sender;
    int AdId = (int)cmd.SelectedValue;


}

enter image description here