0

I'm trying out 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:

<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 :

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

Above code gets the XElement from Music.Xml file

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

Output which I'm getting [![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]

enter image description here

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
Natxo
  • 2,917
  • 1
  • 24
  • 36

1 Answers1

1

Datagrid cannot autogenerate columns when binding to XML data directly, that's one of the (lesser) reasons why you usually want to use a viewmodel.

Actually it works autogenerating columns from the properties of the class of the object you bind it to. That's why you see the properties of XElement in those autogenerated columns.

If you want to bind to XML you will have to declare your columns:

<DataGrid.Columns>
    <DataGridTextColumn Binding="{Binding Path=Attribute[Title].Value}" Header="Title" />
    <DataGridTextColumn Binding="{Binding Path=Attribute[Artist].Value}" Header="Artist"/>
    <DataGridTextColumn Binding="{Binding Path=Attribute[ReleaseDate].Value}" Header="ReleaseDate"/>
</DataGrid.Columns>
Natxo
  • 2,917
  • 1
  • 24
  • 36
  • Thank you Natxo. But why is it binding XElement properties to the grid? – Parthasarthi B.K Jun 07 '16 at 08:50
  • Works fine Natxo. But is there any alternative solution for my problem? I don't want to have static DataGridTextColumn. Can't i just bind the XElement to DataGrid just as we do with the List DataGrid Binding? Any help would be really appreciated. – Parthasarthi B.K Jun 07 '16 at 09:06
  • @ParthasarthiB.K I don't think you can do that. You can generate the columns in codebehind, this allows more control in some cases (like when you dont know how many columns will be needed) – Natxo Jun 07 '16 at 09:22
  • Thank you for all your help Natxo :) – Parthasarthi B.K Jun 07 '16 at 09:29