Thursday, November 10, 2011

Binding ListBox with Xml Data using XmlDataProvider


In this post I will demonstrate how to bind xml data with Listbox.

Let’s start with an example.

XAML
<Window x:Class="WpfApplication1.ListBoxWithXmlData"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="Bind ListBox With XmlData" Height="300" Width="300">
<Window.Resources>
<XmlDataProvider x:Key="myCustomers" XPath="Customers">
    <x:XData>
        <Customers xmlns="">
            <Customer Name="Mitesh Sureja" Phone="443322" />
            <Customer Name="Parag Kumar" Phone="558652" />
            <Customer Name="Kalyan S" Phone="654821" />
            <Customer Name="Subrata Banerjee" Phone="225566" />
            <Customer Name="Rama K" Phone="998855" />
            <Customer Name="Jigar Seth" Phone="774411" />
        </Customers>
    </x:XData>
</XmlDataProvider>
</Window.Resources>
<StackPanel>
<TextBlock Text="- Customer list - " Margin="2"
    HorizontalAlignment="Center"/>
<ListBox Margin="5"
         ItemsSource="{Binding Source={StaticResource myCustomers},XPath=*}">
    <ListBox.ItemTemplate>
        <DataTemplate>
                <WrapPanel Margin="3">
                    <TextBlock Text="{Binding XPath=@Name}"
                    Foreground="Red"
                    Margin="0,0,10,0" />
                    <TextBlock Text="{Binding XPath=@Phone}"
                    Foreground="Green"
                    Margin="5,0,0,0"/>
                </WrapPanel>
        </DataTemplate>
    </ListBox.ItemTemplate>
</ListBox>
</StackPanel>

Output

As shown in above example, XmlDataProvider named myCustomers contains collection of Customers and this myCustomers xmldataprovider bind with Listbox’s ItemSource property. ListBox also has datatemplate and template contains two textblocks which are bind with Name and Phone property of myCustomers. So when you run this application listbox shows customer’s name and phone number as shown in above snapshot.

No comments:

Post a Comment