user776676
user776676

Reputation: 4385

LINQ XML query: How do I perform query for binding?

Here's the simplified XML:

<Product>  <Name>Red Chair</Name>  <Price>29.5</Price>   </Product> 

Here's the simplified XAML in which a listbox will display Name and Price per entry:

<ListBox Name="listBox1" ItemsSource="{Binding}"   Margin="10" >            
   <ListBox.ItemTemplate>       
      <DataTemplate>         
         <StackPanel>           
            <TextBlock Text={Binding XPath=./Name} />           
            <TextBlock Text={Binding XPath=./Price} />         
         </StackPanel>       
      </DataTemplate>     
   </ListBox.ItemTemplate> 
</ListBox> 

How do I do the LINQ query in my C# code so that I can do:

 var products = from ... /* I need code between here and next statement */

 listBox1.DataContext = products;

and the listbox is populated with entries from my XML file? Thanks.

Upvotes: 1

Views: 979

Answers (2)

Anas Karkoukli
Anas Karkoukli

Reputation: 1342

And just in case you still have your heart set on XML binding :-) you can use the XmlDataProvider:

 <Window.Resources>
        <XmlDataProvider Source="data.xml" XPath="Products/Product" x:Key="xmlData">
        </XmlDataProvider>
    </Window.Resources>
    <Grid>
        <ListBox Name="listBox1" ItemsSource="{Binding Source={StaticResource xmlData}}"   Margin="10" >
            <ListBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel>
                        <TextBlock Text="{Binding XPath=Name}"  />
                        <TextBlock Text="{Binding XPath=Price}"  />
                    </StackPanel>
                </DataTemplate>
            </ListBox.ItemTemplate>
        </ListBox>

    </Grid>

The previous snippet assumes you have a data.xml file that looks like:

<Products>
  <Product>
    <Name>Product 1</Name>
    <Price>100</Price>
  </Product>
  <Product>
    <Name>Product 2</Name>
    <Price>200</Price>
  </Product>
</Products>

And alternatively of course you set the Source property of the XmlDataProvider programmatically:

public MainWindow()
{
    InitializeComponent();

    (Resources["xmlData"] as XmlDataProvider).Document = YourXDocumentHere;
}

Again, just an FYI!

Upvotes: 0

Jon Skeet
Jon Skeet

Reputation: 1500575

You could try:

var products = doc.Descendants("Product")
                  .Select(x => new { Name = (string) x.Element("Name"),
                                     Price = (decimal) x.Element("Price") });

It's not really clear whether that's what you want, but it might be... you'll then want to change the binding to something like:

<TextBlock Text={Binding Name} />           
<TextBlock Text={Binding Price} />         

You may also want to call ToList to materialize the query once - I don't know enough about XAML binding to know if it caches appropriately for you. (I'd imagine it does, but...)

Upvotes: 4

Related Questions