bind the data to ComboBox

时间:2017-04-24 17:18:22

标签: c# wpf combobox

I have following class

public class ComboData 
{

 public int Id { get; set;}

 public string Value { get; set;}

 public string description { get; set;}

}

I'm binding data to combo box like following

List<ComboData> ListData = new List<ComboData>();
ListData.Add(new ComboData { Id = "1", Value = "One" });
ListData.Add(new ComboData { Id = "2", Value = "Two" });
ListData.Add(new ComboData { Id = "3", Value = "Three" });
ListData.Add(new ComboData { Id = "4", Value = "Four" });
ListData.Add(new ComboData { Id = "5", Value = "Five" });

cbotest.ItemsSource = ListData;
cbotest.DisplayMemberPath = "Value";
cbotest.SelectedValuePath = "Id";

cbotest.SelectedValue = "2";

now I changed my code to get above hard coded values from following Entity Framework GetAll method

public class DAL
{
    Dbcontext db = new Dbcontext();

    public List<ComboData> GetAll()
    { 
        var sp = db.ComboDatas.ToList();  
        return sp;  
    }
}

How can I bind this values to above cbotest.ItemsSource directly with Id and Value ?

1 个答案:

答案 0 :(得分:1)

It will be, just assign the function to the ItemsSource which will return a List of ComboData

cbotest.ItemsSource = GetAll();
cbotest.DisplayMemberPath = "Value";
cbotest.SelectedValuePath = "Id";
cbotest.SelectedValue = "2";