Introduction
What's Data Binding: Data binding is the process that establishes a connection between the application User Interface and business logic.
This sample explain how to Bind Data to a Grid View using XML file.
This is a simple way the 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 rename it DataBinding.
Description
How does this sample solve the problem?
First, I added a Grid View 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>
Than, created a XML file Fruits.XML in the common file to store the data of solution explorer:
- <?xml version="1.0" encoding="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>
Also, created a new Class Fruits.cs
And added two statments.
- 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 automaticlly 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;
- }