Bind an ObservableCollection to a ComboBox in WPF

c# data-binding entity-framework linq wpf

Question

I'm using Entity Framework as my database source and need to convert a Linq query "var" type to an ObservableCollection. I then need to bind the ObservableCollection to a ComboBox on WPF form; binding to ItemsSource, DisplayMemeberPath, SelectedValuePath and SelectedValue.

Here is Code:

using (PulseContext pc = new PulseContext())
{
    var maritalcodes =  from m in pc.CodeMaster
                        where m.Type == "16"
                        select new { m.Code, m.Description };

    prop.ClientData.Options = new ObservableCollection<object>(maritalcodes);
}

Problem is the ComboBox is showing this as "{ Code = ????, Description = ???? }" instead of bind to code for value and description for display. What do I have to do to get the ComboBox to bind to the individual elements?

1
2
1/15/2017 6:15:28 PM

Accepted Answer

You need to set SelectedValuePath and DisplayMemberPath like this:

prop.ClientData.Options = new ObservableCollection<object>(maritalcodes);
prop.ClientData.Options.SelectedValuePath = "Code";
prop.ClientData.Options.DisplayMemberPath = "Description";

Or you can set them in xaml like this:

<ComboBox ItemsSource="{Binding Path=maritalcodes}"
          SelectedValuePath="Code"
          DisplayMemberPath="Description" />
3
7/18/2012 10:41:38 PM

Popular Answer

<ComboBox ItemsSource="{Binding Path=maritalcodes}"
      SelectedValuePath="Code"
      DisplayMemberPath="Description" 
      SelectedValue="{Binding Path=Code}"/>

I hope this will help.



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow