I\'ve been trying to bind XML (via an XElement) to a DataGrid dynamically in Silverlight (specifically Silverlight 4, but any solutions in SL3 would be fine too) but have be
Below is another alternative that may also help. It's a bit of a hack.
It's written and tested using Silverlight 3.The ViewModel:
namespace DatagridXml
{
public class TestViewModel
{
public TestViewModel()
{
XmlData = @"Name1 21 Address1Name2 22 Address2Name3 23 Address3 ";
}
public string XmlData { get; set; }
}
}
The value converter:
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows.Controls;
using System.Windows.Data;
using System.Xml.Linq;
namespace DatagridXml
{
public class XmlColumnConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
string elementToGenerate = parameter.ToString();
DataGrid control = value as DataGrid;
control.Columns.Clear();
var result = new List>();
XDocument xmlDoc = XDocument.Parse(control.DataContext.ToString());
// Generate Columns
var columnNames = xmlDoc.Descendants(elementToGenerate).FirstOrDefault();
int pos = 0;
foreach (var columnName in columnNames.Elements())
{
var column = new DataGridTextColumn();
column.Header = columnName.Name;
column.Binding = new Binding("[" + pos + "]");
control.Columns.Add(column);
pos++;
}
// Parse elements to generate column's data
foreach (var element in xmlDoc.Descendants(elementToGenerate))
{
var row = new List();
foreach (var column in element.Elements())
{
row.Add(column.Value);
}
result.Add(row);
}
return result;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotSupportedException("Cannot convert to xml from list.");
}
}
}
And, you use like this: