简体   繁体   中英

Getting property value in ComboBox in WPF

I have a comboBox and it is binded to list (from database, using entity framework). I would like to get an AdId of the selected item(object) on SelectionChanged of comboBox.

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
}

The cmd.SelectedItem property of the ComboBox will returns an object, you can cast them to your own business object. and then you can easily access its properties like the following:

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

Set SelectedValuePath="AdId"

And get selected value from code as follow,

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


}

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM