简体   繁体   中英

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.

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...)

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!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM