简体   繁体   English

将ObservableCollection绑定到WPF中的ComboBox

[英]Bind an ObservableCollection to a ComboBox in WPF

I'm using Entity Framework as my database source and need to convert a Linq query "var" type to an ObservableCollection. 我使用Entity Framework作为数据库源,需要将Linq查询“ var”类型转换为ObservableCollection。 I then need to bind the ObservableCollection to a ComboBox on WPF form; 然后,我需要将ObservableCollection绑定到WPF表单上的ComboBox; binding to ItemsSource, DisplayMemeberPath, SelectedValuePath and SelectedValue. 绑定到ItemsSource,DisplayMemeberPath,SelectedValuePath和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. 问题是ComboBox将其显示为“ {Code = ????,Description = ????}”,而不是绑定到代码以显示值和描述。 What do I have to do to get the ComboBox to bind to the individual elements? 我要怎么做才能将ComboBox绑定到各个元素?

You need to set SelectedValuePath and DisplayMemberPath like this: 您需要这样设置SelectedValuePathDisplayMemberPath

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: 或者您可以像这样在xaml中设置它们:

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

I hope this will help. 我希望这将有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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