Search code examples
wpfdata-bindingdatagridexpression-blend

datagrid binding xaml


I'm trying to bind datagrid to xml:

<StackPanel.DataContext>
<XmlDataProvider Source="bill.xml" XPath="/Foods/Food"/>
</StackPanel.DataContext>

<DataGrid Width="190" Height="200" HorizontalAlignment="Center" VerticalAlignment="Top" Foreground="Black" ItemsSource="{Binding}">

<DataGrid.Columns>
<DataGridTextColumn Header="Quantity" FontSize="12" Binding="{Binding XPath=/Foods/Food/Quantity}" />
<DataGridTextColumn Header="Item" FontSize="12" Binding="{Binding XPath=/Foods/Food/Item}"/>
<DataGridTextColumn Header="Price" FontSize="12" Binding="{Binding XPath=/Foods/Food/Price}"/>
<DataGridTextColumn Header="P" FontSize="12" Binding="{Binding XPath=/Foods/Food/P}"/>
<DataGridTextColumn Header="C" FontSize="12" Binding="{Binding XPath=/Foods/Food/C}"/>          
</DataGrid.Columns>

</DataGrid>

XML:

<?xml version="1.0" encoding="utf-8" ?>
    <Foods>
      <Food>
        <Quantity>1</Quantity>
        <Item>SMALL COFFEE</Item>
    <Price>0.95</Price>
    <P>N</P>
    <C>1</C>
      </Food>
    <Food>
        <Quantity>1</Quantity>
        <Item>CHEESE CAKE</Item>
    <Price>4.50</Price>
    <P>N</P>
    <C>1</C>
      </Food>
    <Food>
        <Quantity>1</Quantity>
        <Item>SPAGHETTI</Item>
    <Price>13.50</Price>
    <P>N</P>
    <C>1</C>
      </Food>

    </Foods>

DataGrid show nothing.

Did I miss something?


Solution

  • Your XmlDataSource is already taking all nodes /Foods/Food so you don't need to specify that part of the XPath again in your bindings. Try removing it, thus:

    <DataGridTextColumn Header="Quantity" FontSize="12" Binding="{Binding XPath=Quantity}" />