user776676
user776676

Reputation: 4385

How to display XML data in XAML listbox programmatically?

I have an XML file, each element has name of a product and it's price.

I have a XAML file with a listbox.

How do I display all the items in the XML file in the listbox programmatically in C#? Thanks.

Here is my XML file with 3 sample products:

<?xml version="1.0" encoding="UTF-8"?>
<dataroot xmlns:od="urn:schemas-microsoft-com:officedata" generated="2011-09-20T15:04:12">
<Product>
<Name>Red Chair</Name>
<Price>29.5</Price>
</Product>
<Product>
<Name>Blue Chair</Name>
<Price>27</Price>
</Product>
<Product>
<Name>Round Table</Name>
<Price>31</Price>
</Product>
</dataroot>

Here's my XAML:

<Window x:Class="DockPanel.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Inventory" Height="350" Width="525">
 <DockPanel>

    <ListBox Name="listBox1" Margin="10" >


    </ListBox>

</DockPanel>

Upvotes: 0

Views: 2444

Answers (1)

Steve Greatrex
Steve Greatrex

Reputation: 15999

You want to use an XmlDataProvider (explained here). You'll need to out the provider in your Resources, speci path to get the data you want displayed, and then bind your ItemsSource to the resource

Upvotes: 1

Related Questions