WPF data binding from XML file to DataGrid

If you are not familiar to WPF (Windows Presentation Foundation) it is pain in the butt. But you need to be persistent. It is not as difficult as you think it is!

DataGrid is one of controls you can use in your WPF project. Why is it so necessary? For example, you can use it to show your data stored in a database, XML file etc. When you create small applications which simplify your life it is a good way to store data in XML files.

How to bind data to DataGrid and create a simple application which uses that?

1. Open Visual Studio 2010 or 2012 (in this example it doesn’t matter, but I will present it using VS 2010 Ultimate)

2. File -> New -> Project -> Visual C# -> Windows -> WPF Application. Name it and click OK.

3. In this example I am going to store people data, so the best way is to create a new class called „Person.cs”. Add it to your project. Create several properties which describes each person. Then add XmlElement structure to each of these (as it was shown in this article.

namespace DefaultApp
{
    using System.Xml.Serialization;

    public class Person
    {
        [XmlElement("Name")]
        public string Name { get; set; }

        [XmlElement("Surname")]
        public string Surname { get; set; }

        [XmlElement("PhoneNo")]
        public string PhoneNo { get; set; }

        [XmlElement("Country")]
        public string Country { get; set; }
    }
}

4. Then in XAML file – creator has already added this, it is called MainWindow.xaml – add DataGrid from Toolbox. When it is already added you can see something like this:

<DataGrid AutoGenerateColumns="False" Height="254" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataGrid" VerticalAlignment="Top" Width="479" />

Now you need to modify it by adding property called ItemsSource to set a binding path to a „Person.cs” class.

<DataGrid AutoGenerateColumns="False" Height="254" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataGrid" VerticalAlignment="Top" Width="479"
ItemsSource="{Binding Path=Elements[Person]}" />

5. Now you need to add Columns to your DataGrid with binding paths to each element of „Person.cs” class. It should look like this:

<DataGrid AutoGenerateColumns="False" Height="254" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataGrid" VerticalAlignment="Top" Width="479" ItemsSource="{Binding Path=Elements[Person]}" >
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Path=Element[Name].Value}" />
<DataGridTextColumn Header="Surname" Binding="{Binding Path=Element[Surname].Value}"/>
<DataGridTextColumn Header="Phone no" Binding="{Binding Path=Element[PhoneNo].Value}"/>
<DataGridTextColumn Header="Country" Binding="{Binding Path=Element[Country].Value}"/>
</DataGrid.Columns>
</DataGrid>

6. Whole code of MainWindow.xaml look similar to this:

<Window x:Class="DefaultApp.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="MainWindow" Height="350" Width="525">
<Grid>
<DataGrid AutoGenerateColumns="False" Height="254" HorizontalAlignment="Left" Margin="12,12,0,0" Name="dataGrid" VerticalAlignment="Top" Width="479" ItemsSource="{Binding Path=Elements[Person]}" >
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Binding="{Binding Path=Element[Name].Value}" />
<DataGridTextColumn Header="Surname" Binding="{Binding Path=Element[Surname].Value}"/>
<DataGridTextColumn Header="Phone no" Binding="{Binding Path=Element[PhoneNo].Value}"/>
<DataGridTextColumn Header="Country" Binding="{Binding Path=Element[Country].Value}"/>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Window>

7. Now add button to your MainWindow by choosing it from a Toolbox menu. Click 2 times on it and you will move to behind code file „MainWindow.xaml.cs”. Go to your button click event and add this code:

var peopleList =
                XElement.Load(/*@"path to your xml file"*/);
            this.dataGrid.DataContext = peopleList;

It will look similar to this:

using System.Windows;

namespace DefaultApp
{
    using System.Xml.Linq;

    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void RefreshButtonClick(object sender, RoutedEventArgs e)
        {
            var peopleList =
                XElement.Load(/*@"path to your xml file"*/);
 this.dataGrid.DataContext = peopleList;
 }
 }
}

8. Prepare your own XML file. It can look like below (I named it People.xml) or you can also use serialization and deserialization in your application to create it.

<?xml version="1.0" encoding="utf-8"?>
<ArrayOfPerson xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
  <Person>
    <Name>John</Name>
    <Surname>Jones</Surname>
    <PhoneNo>333333333111</PhoneNo>
    <Country>Germany</Country>
  </Person>
  <Person>
    <Name>Ben</Name>
    <Surname>Benny</Surname
    <PhoneNo>222222222111</PhoneNo>
    <Country>Spain</Country>
  </Person>
  <Person>
    <Name>Jack</Name>
    <Surname>Jacks</Surname>
    <PhoneNo>555555555111</PhoneNo>
    <Country>Italy</Country>
  </Person>
</ArrayOfPerson>

9. Now you can rebuild and debug your application. After clicking the button your DataGrid will fill all rows with data from XML file:

WPFdefault

Jedna uwaga do wpisu “WPF data binding from XML file to DataGrid

Zostaw komentarz

Wprowadź swoje dane lub kliknij jedną z tych ikon, aby się zalogować:

Logo WordPress.com

Komentujesz korzystając z konta WordPress.com. Wyloguj /  Zmień )

Zdjęcie na Google+

Komentujesz korzystając z konta Google+. Wyloguj /  Zmień )

Zdjęcie z Twittera

Komentujesz korzystając z konta Twitter. Wyloguj /  Zmień )

Zdjęcie na Facebooku

Komentujesz korzystając z konta Facebook. Wyloguj /  Zmień )

w

Connecting to %s