namespace datagrid
{ public partial class Page : UserControl
{ public Page()
{ InitializeComponent();
}
private void constructdg()
{ //generic xml returned from a service
String xml = "<SqlXml empid=\"varchar\" deptid=\"varchar\" empname=\"varchar\"><row empid=\"1001\" deptid=\"1\" empname=\"Sam\" /><row empid=\"1002\" deptid=\"3\" empname=\"Bill\" /></SqlXml>";
DataGrid dg = new DataGrid();
dg.AutoGenerateColumns = false;
XmlReader xmlReader = XmlReader.Create(new StringReader(xml));
//list containing the row elements
List<Dictionary<string, string>> list = new List<Dictionary<string, string>>();
//create the columns of the datagrid from the first node
while(xmlReader.Read())
{ if (xmlReader.HasAttributes)
{ //check if the first node
if (xmlReader.IsStartElement("SqlXml")) { //construct the columns of the dg
while (xmlReader.MoveToNextAttribute())
{ DataGridTextColumn dtextcol = new DataGridTextColumn();
dtextcol.IsReadOnly = true;
dtextcol.Header = xmlReader.Name;
indexingConverter convert = new indexingConverter();
Binding bind = new Binding { Converter = convert, ConverterParameter = xmlReader.Name ; dtextcol.DisplayMemberBinding = bind;
dg.Columns.Add(dtextcol);
}
}
else
{ //construct the rows
Dictionary<string, string> d = new Dictionary<string, string>();
while (xmlReader.MoveToNextAttribute())
{ d.Add(xmlReader.Name, xmlReader.Value);
}
list.Add(d);
}
//move the reader to elements
xmlReader.MoveToElement();
}
}
dg.ItemsSource = list;
LayoutRoot.Children.Add(dg);
}
private void Button_Click(object sender, RoutedEventArgs e)
{ constructdg();
}
}
class indexingConverter : IValueConverter
{ public object Convert(object value, Type targetType, object parameter, ystem.Globalization.CultureInfo culture)
{ Dictionary<string, string> columnData = (Dictionary<string, string>)value;
return columnData[parameter.ToString()];
}
public object ConvertBack(object value, Type targetType, object parameter, ystem.Globalization.CultureInfo culture)
{ throw new NotImplementedException();
}
}
}