In Silverlight, datadrid binds XML data and transfers it from a foreign website. For more information, see
Bind a given DataGrid data source to a given XML file
DataGrid cocould also be bound to a another persisted kind of datasoures, such as XML ressources or something spectial such as RSS feeds. to bind a given DataGrid to a given XML file data source, the following example is provided to restrict strate that.
Create a new Silverlight Application
Figure 1
First, in The XAML code editor Add the following code
<Grid X: Name = "layoutroot" background = "white">
<Data: DataGrid X: Name = "mydatagrid"
Autogeneratecolumns = "true"
>
</Data: DataGrid>
</GRID>
As you can remark, the DataGrid shocould be named so that it cocould be refered later in the C # code behind. Now, let consider this XML file as a main data source for our DataGrid.
<? XML version = "1.0" encoding = "UTF-8"?>
<Myfamily>
<Item>
<Firstname> bejaoui </firstname>
<Lastname> Habib </lastname>
<Age> 66 </age>
<Ismale> true </ismale>
</Item>
<Item>
<Firstname> Ben garga </firstname>
<Lastname> kadija </lastname>
<Age> 63 </age>
<Ismale> false </ismale>
</Item>
<Item>
<Firstname> bejaoui </firstname>
<Lastname> Bechir </lastname>
<Age> 30 </age>
<Ismale> true </ismale>
</Item>
<Item>
<Firstname> bejaoui </firstname>
<Lastname> Arbia </lastname>
<Age> 25 </age>
<Ismale> false </ismale>
</Item>
<Item>
<Firstname> bejaoui </firstname>
<Lastname> rim </lastname>
<Age> 20 </age>
<Ismale> false </ismale>
</Item>
</Myfamily>
Second, a class that fits the XML structure shocould be developed. It cocould be represented as under
Public class person
{
Public String firstname {Get; set ;}
Public String lastname {Get; set ;}
Public String age {Get; set ;}
Public String ismale {Get; set ;}
}
Third, a reference to the system. xml. LINQ namespace shocould be added
Figure 2
In the code behind, a DataGrid object shocould be declared and the under Code shocould be implemented
Public partial class page: usercontrol
{
DataGrid ogrid;
Public page ()
{
Initializecomponent ();
Initializegrid ();
}
Public void initializegrid ()
{
Xdocument odoc = xdocument. Load ("file. xml ");
VaR mydata = from info in odoc. descendants ("item ")
Select new person
{
Firstname = convert. tostring (info. element ("firstname"). value ),
Lastname = convert. tostring (info. element ("lastname"). value ),
Age = convert. tostring (info. element ("Age"). value ),
Ismale = convert. tostring (info. element ("ismale"). value)
};
Ogrid = This. findname ("mydatagrid") as DataGrid;
Ogrid. itemssource = mydata;
}
}
This leads to the following result