Click here to Skip to main content
15,885,216 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I'm trying XElement binding for the very first time so apologies if this is very silly. I have an XML which I need to bind to DataGrid.

Music.xml:
XML
<Music>
    <Album Title="Chris Sells Live" Artist="Chris Sells" ReleaseDate="2/5/2008" /> 
    <Album Title="The Road to Redmond" Artist="Luka Abrus" ReleaseDate="4/3/2008"/> 
    <Album Title="The Best of Jim Hance" Artist="Jim Hance" ReleaseDate="6/2/2008"/> 
</Music>


CodeBehind :
C#
InitializeComponent();
XElement MyMusic = XElement.Load("Music.xml"); 
this.XElementContainer.DataContext = MyMusic.Elements("Album");


Above code gets the XElement from Music.Xml file

XAML :
HTML
<DataGrid x:Name="XElementContainer" ItemsSource="{Binding}"/>


OutputWindow.jpg - Google Drive

The above link contains the output of the current execution where it is binding the properties of XElement.I need to bind the child element of specified node i.e Album which has child nodes of Title, Artist and Release Date.
As you see the image, why is it Binding Properties of XElement? How do i get rid of this?
I'm expecting the output in datagrid where I dont want to create any static DataGridTextColumn. Is it possible to just bind the XElement data and get a result like this:

Title |Artist |ReleaseDate
Chris Sells Live Chris Sells 2/5/2008
the Road to Redmond Luka Abrus 4/3/2008
the Best of Jim Hance Jim Hance 6/2/2008

What I have tried:

I'm very new to XElement binding. so what ever posted above is what I have tried.
Posted
Updated 7-Jun-16 17:10pm
v2
Comments
George Jonsson 7-Jun-16 6:05am    
Does it have to be XElement or could you use DataTable?
partha143 7-Jun-16 6:13am    
Priority is to use XElement. But it would be grateful if you could give me some idea on both the approach.
George Jonsson 7-Jun-16 7:01am    
Sorry, no time tonight.
A DataTable is not that difficult to use.
DataTable dt = new DataTable():
dt.ReadXml(path);

Set the data source in the code behind
dataGrid.ItemSource = dt.DefaultView;
partha143 8-Jun-16 2:53am    
Thanks George. Worked fine :)

1 solution

Hi Partha

use DataSet you need following code in ur code behind

C#
InitializeComponent();
System.Data.DataSet ds = new System.Data.DataSet();
ds.ReadXml("Music.xml"); 
this.XElementContainer.DataContext = ds.Tables[0];
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900