我们有 40 个 xml 文件。我们想动态绑定到数据网格。例如,不同结构的 40 个 xml 文件
a xml file :
<a>
<at1="val1" at2="val2" >
<at1="val4" at2="val5" >
<at1="val7" at2="val8" >
<at1="val10" at2="val11" >
</a>
b xml file:
<b>
<at1="val1" at2="val2" at3="val3" >
<at1="val4" at2="val5" at6="val6">
<at1="val7" at2="val8" at3="val9">
<at1="val10" at2="val11" at3="val12">
</b>
c xml file:
<c>
<at1="val1" at2="val2" at3="val3" at13="vall3">
<at1="val4" at2="val5" at6="val6" at14="val14">
<at1="val7" at2="val8" at3="val9" at15="val15">
<at1="val10" at2="val11" at3="val12" at16="val16">
</c>
动态代码:
XElement TrackList = XElement.Parse("a.xml");
var atributs = TrackList.Descendants("a").Attributes();
foreach (var item in atributs)
{
DataGridTextColumn cc=new DataGridTextColumn();
cc.Header = item.Name;
Binding myBinding = new Binding("Attribute[" + item.Name.ToString() + "].Value");
myBinding.Source = datagrid1;
//LibViadat.SetBinding(TextBlock.TextProperty, myBinding);
cc.Binding = myBinding;
datagrid1.Columns.Add(cc);
}
datagrid1.DataContext = TrackList;
datagrid1.Visibility = Visibility.Visible;