Question

XElement Doc.

<forms xmlns="">
  <form>
    <id>1361</id>
    <name>TEST3</name>
  </form>
  <form>
    <id>1658</id>
    <name>TEST4</name>
  </form>
  <form>
    <id>1975</id>
    <name>Mac New Patient</name>
  </form>
  <form>
    <id>2209</id>
    <name>Test Atlantic</name>
  </form>
  <form>
    <id>2565</id>
    <name>Rice Creek Test</name>
  </form>
</forms>

Code behind

 XElement xmlForms = data.GetXmlForm();
 var ElementsList = from c in xmlForms.Element("Forms").Descendants("form")
 select new { Name = c.Element("name").Value, ID = c.Element("id").Value };

 cBox_NewPat.DataContext = ElementsList; 
 cBox_NewPat.DisplayMemberPath = "name";
 cBox_NewPat.SelectedValuePath = "id";

I need to bind data(name, id) from XElement to WPF Combobox. For some reason, its not working, not even get the data from XML into the Element List.

Was it helpful?

Solution

The property names are case sensitive.

You need to change

cBox_NewPat.DisplayMemberPath = "name";
cBox_NewPat.SelectedValuePath = "id";

To

cBox_NewPat.DisplayMemberPath = "Name";
cBox_NewPat.SelectedValuePath = "ID";

to match your anonymous type.

OTHER TIPS

It looks like you are missing several things here (aside from the null result - I will get to it below).

  1. you need to set ItemsSource property on the combobox.

    cBox_NewPat.ItemsSource = ElementsList
    
  2. you should use

    cBox_NewPat.DisplayMemberPath = "Name"; 
    

    instead of

    cBox_NewPat.DisplayMemberPath = "name";
    

    since your anonymous type property is called "Name", not "name". The same with SelectedValuePath

  3. please show what you do in GetXmlForm method - this is where something goes wrong. If you do XElement.Parse(xmlString), then it will work if you remove the namespace attribute (xmlns) from the forms element. you will also need to use

    xmlForms.Descendants("form")
    

    instead of

    xmlForms.Element("forms").Descendants("form")
    
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top