Introduction
What's Data Binding: Data binding is the process that establishes a connection between the application User Interface and business logic.
This sample explains how to Bind Data to a Grid View using XML file.
This is a simple way to store data because you just need an XML file to store and transport data.
So this sample is very helpful for your Windows store applications.
Building the Sample
I used Visual Studio 2012 Ultimate edition.
I created a new project (Blank application C#) and renamed it DataBinding
.
Description
How does this sample solve the problem?
First, I added a GridView
control with item and data templates to bind data to the GridView
control as follows:
<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
<GridView x:Name="DataGrid1">
<GridView.ItemTemplate>
<DataTemplate>
<Grid Background="Red" Width="300" Height="100">
<TextBlock Text="{Binding Title}"></TextBlock>
</Grid>
</DataTemplate>
</GridView.ItemTemplate>
</GridView>
</Grid>
Then, I created an XML file Fruits.XML in the common file to store the data of solution explorer:
="1.0"="utf-8"
<Fruits>
<Fruits name="Apple"/>
<Fruits name="Apricot "/>
<Fruits name="Banana"/>
<Fruits name="Blackberry"/>
<Fruits name="Blackcurrant "/>
<Fruits name="Lemon"/>
<Fruits name="Mango"/>
</Fruits>
I also created a new class Fruits.cs and added two statements.
using System.Xml.Linq; using Windows.ApplicationModel;
using System.Xml.Linq;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml.Linq;
using Windows.ApplicationModel;
namespace DataBinding
{
class Fruits
{
public string Title { get; set; }
}
}
Finally, the XML file will automatically synchronize with our controls after adding this code:
protected override void OnNavigatedTo(NavigationEventArgs e)
{
string peopleXMLPath = Path.Combine(Package.Current.InstalledLocation.Path, "Common/Fruits.xml");
XDocument loadedData = XDocument.Load(peopleXMLPath);
var data = from query in loadedData.Descendants("Fruits")
select new Fruits
{
Title = (string)query.Attribute("name")
};
DataGrid1.ItemsSource = data;
}