Search code examples
wpfxmlbindingdatagridxelement

WPF XAML Datagrid XML File Binding with XElement, XML File Loaded in codebehind


Here we go again kids, yet another camper lost in the woods around WPF Databinding. Its been a fruitful day of climbing the databinding inverted ice wall, but I'm at my wits end with this. No examples I find or amount of SNOOP'ing is helping me find my issue. Hopefully some databinding rock star, all three of you, can help a brotha out! :)

XML File - The faces and names have been changed to protect the innocent

    <?xml version="1.0" encoding="utf-8" ?>
<Mappings>
  <Mapping>
    <Class1>WonderBread</Class1>
    <Class2>Tortilla</Class2>
    <Properties>
      <Property>
        <Jx>name</Jx>
        <Dyn>Name</Dyn>
        <Create>1</Create>
        <Update>0</Update>
      </Property>
      <Property>
        <Jx>Juice</Jx>
        <Dyn>Juice</Dyn>
        <Create>1</Create>
        <Update>0</Update>
      </Property>
      <Property>
        <Jx>Fred</Jx>
        <Dyn>Fred</Dyn>
        <Create>1</Create>
        <Update>0</Update>
      </Property>
      <Property>
        <Jx>Love</Jx>
        <Dyn>Love</Dyn>
        <Create>1</Create>
        <Update>0</Update>
      </Property>
    </Properties>
  </Mapping>
</Mappings>

How I load this XML File and set it into my datagrids DataContext. Done in the constructor. This loads correctly, via SNOOP I can see the XML file in the DataContext.

    // load the ObjectMappingXML file and set as Gridview Context
    XEClassMappings = XElement.Load(ConfigurationManager.AppSettings["ClassMappingXML"]);
    dgMapping.DataContext = XEClassMappings;

XAML code to display the content

        <DataGrid x:Name="dgMapping" ItemsSource="{Binding Path=Elements[Property]}" Height="569">
            <DataGrid.Columns >
                <DataGridTextColumn Header="JxAPI Prop" Binding="{Binding Path=Element[Jx].Value}"/>
                <DataGridTextColumn Header="Dyn Prop" Binding="{Binding Path=Element[Dyn].Value}"/>
            </DataGrid.Columns>
        </DataGrid>

What in the name of all that is holy am I missing? 8hrs of hopeful F5s has left me at wits end...


Solution

  • You will have to reach to the properties element. Change your ItemsSource binding to below:

    <DataGrid x:Name="dgMapping" ItemsSource="{Binding Path=Element[Mapping].Element[Properties].Elements[Property]}" Height="569">
    

    It will work.

    Hope it helps