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