Load XML file [Windows Store]

Download source

Steps:

  • Create / Load XML file.
  • Read XML file data.
  • Bind XML data with UI Control.

What?

XML: stands for “Extensible Markup Language” based on “tags” and “name-value” pairs. [wiki]

Why?

you may need this technique to load some static data to your application in organized way.

How?

Create XML File: PROJECT >> Add New Item.

s1

Select meaningful name for the file, and start writing you data in suitable hierarchy.

s2

<?xml version="1.0" encoding="utf-8" ?>
<Flags>
 <Flag>
  <FlagImage>1.png</FlagImage>
  <FlagTitle>Flag of Ottoman Egypt</FlagTitle>
  <FlagDescription>(1793-1844)</FlagDescription>
 </Flag>
...
</Flags>

now, lets read the XML file an create a list of Flags
First: create new class “Flags”

s3

class Flag
{
 public string FlagImage { set; get; }
 public string FlagTitle { set; get; }
 public string FlagDescription { set; get; }</em>

 public Flag(string image, string title, string description)
 {
  FlagImage = "ms-appx:///Assets/" + image;
  FlagTitle = title;
  FlagDescription = description;
 }
}

Secound: Create list of the “Flags” in “MainPage.xaml.cs”

XDocument xmlDoc = XDocument.Load("Flags Of Egypt.xml");
IEnumerable<Flag> flags = from item in xmlDoc.Descendants("Flag")
 select
 new Flag(item.Element("FlagImage").Value,
 item.Element("FlagTitle").Value,
 item.Element("FlagDescription").Value);

and finally bind this list with the UI element “Data Grid View”

UIFlags.ItemsSource = flags;

in the UI “MainPage.xaml”
the data grid view will looks like:

<GridView
 x:Name="UIFlags"
 SelectionMode="None"
 ItemsSource="{Binding}"
 HorizontalAlignment="Center"
 VerticalAlignment="Center">

 <GridView.ItemTemplate>
 <DataTemplate>
 <StackPanel
 Margin="5"
 Orientation="Vertical"
 Background="#FF414141">
 <Image
 Source="{Binding FlagImage}"
 Width="200"
 Height="150"/>
 <TextBlock
 Text="{Binding FlagTitle}"
 Foreground="White"
 HorizontalAlignment="Center"/>
 <TextBlock
 Text="{Binding FlagDescription}"
 Foreground="White"
 HorizontalAlignment="Center"
 Margin="0,0,0,10"/>
 </StackPanel>
 </DataTemplate>
 </GridView.ItemTemplate>
</GridView>

Result:
screenshot_03132013_124104

Flags information collected from:
http://en.wikipedia.org/wiki/Flag_of_Egypt

5 thoughts on “Load XML file [Windows Store]

  1. Pingback: Create User Control with customized events | Technical Blog

Leave a comment