Search code examples
c#wpfxmlcomboboxxelement

How to bind data from XElement to combobox


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.


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.