views:

454

answers:

1

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?

+2  A: 

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}" />
Aviad P.
ok, now it shows all values in design view, but when I run application it's empty. Should I add code in code behind, something like: DataGrid.Bind()?
Alex
Data shows in design time but not in run time?? Weird! You must be doing something wrong in code behind to neutralize the data source.
Aviad P.
Actually I don't do anything in code behind, I just use Expression Blend for design.
Alex
It's probably an issue of the executable failing to locate the xml file when it's running, because it's running from inside the `bin\debug` folder, but when in design view, it has the current directory of the project (where the xml file resides).
Aviad P.
Thanks, I specified full path to xml and it's working now.
Alex