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.
Select meaningful name for the file, and start writing you data in suitable hierarchy.
<?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”
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>
Flags information collected from:
http://en.wikipedia.org/wiki/Flag_of_Egypt
You present this beautifully. Thank you for showing how to do this.
Thanks Steve, You are welcome.
Bro, I not understand on “XDocument” , please tell me what is it? and how I create it? Thanks
System.Xml.Linq namespace is one of the .NET framework namespaces, contains an interface that enables you to work with XML documents easily
see this: http://msdn.microsoft.com/en-us/library/system.xml.linq.xdocument.aspx
Pingback: Create User Control with customized events | Technical Blog