WPF: Binding XML Data to UI Elements

In this article, we will see how to bind XML data to WPF UI Elements. In this demonstration, I will try to show you a simple Master-Detail sample. I have used the following WPF controls in this example –

1) DataGrid.
2) TextBox.
3) Image.

So let’s add a XML file to our WPF project and call it ‘Customers.xml’. Now add some dummy data as shown below –

<?xml version="1.0" encoding="utf-8" ?>
<Customer CustomerID="98886" Name="Pravinkumar R. D." City="Pune">
<ProductName>Samsung Monitor</ProductName>
<Customer CustomerID="98887" Name="Alisha C." City="Mumbai">
<ProductName>Samsung LCD</ProductName>
<Customer CustomerID="98888" Name="Yash D." City="Delhi">
<ProductName>Samsung iPAD</ProductName>
<Customer CustomerID="98889" Name="Mahesh S." City="Mumbai">
<ProductName>Samsung Laptop</ProductName>

For this demonstration, I have added a folder called ‘Images’ in the WPF project, with a few sample images. Now let’s add a XML data source in our XAML code, which will fetch the data from our XML file ‘Customers.xml’ as shown below –


After this step, let’s design the main UI which will display all the customers in a Datagrid control. When we choose a specific customer by selecting a DataGrid row, it will show the detailed order for that customer. For this let’s add some XAML code as shown below –

<RowDefinition Height="130*" />
<RowDefinition Height="181*" />

<DataGrid x:Name="dataGrid1" Margin="8,8,8,0" 
AutoGenerateColumns="False" ItemsSource="{Binding}" 
Height="114" VerticalAlignment="Top" 
IsSynchronizedWithCurrentItem="True" Grid.Row="0">
<DataGridTextColumn Binding="{Binding XPath=@CustomerID}" 
<DataGridTextColumn Binding="{Binding XPath=@Name}" 
<DataGridTextColumn Binding="{Binding XPath=@City}" 

<StackPanel Orientation="Vertical" Grid.Row="1">
<StackPanel Orientation="Horizontal">
<TextBlock Text="Order No."/>
<TextBox Text="{Binding XPath=OrderNo}" Width="83" />
<StackPanel Orientation="Horizontal">
<TextBlock Text="Product Name"/>
<TextBox Text="{Binding XPath=ProductName}"/>
<StackPanel Orientation="Horizontal">
<TextBlock Text="Product Price"/>
<TextBox Text="{Binding XPath=Price}"/>
<StackPanel Orientation="Horizontal">
<Image Source="{Binding XPath=Picture}" Height="100" 

If you observe, the DataGrid property ‘IsSynchronizedWithCurrentItem’ is set to true. This means, when we make a choice of the DataGrid row, the corresponding item will be shown below as a details view in the TextBox control. It will also show an image of the product in an Image control.

Now when you run the project and select any row of the DataGrid, the output will look similar to the following –


Mufto said...

Goody! Can the same be done for a Silverlight Grid too. I do not have a a machine with VS now so thought of asking you directly.

Pravinkumar said...

Hi Mufto,

You can not do the same in Silverlight. However, in Silverlight 4.0, there are few capabilities which you can use. Please go through this link -