1.xml文件 VMInfo.xml
<?xml version="1.0" encoding="utf-8"?> <MachineInfo> <machine name="cosapx2"> <OS>32</OS> <IE>Win7</IE> <OFFICE>2013</OFFICE> </machine> <machine name="cosapxqa5"> <OS>64</OS> <IE>Win8</IE> <OFFICE>2013 std.</OFFICE> </machine> </MachineInfo>
2.Xmal中加载xml数据
<Window.Resources> <XmlDataProvider x:Key="vminfo" Source="VMInfo.xml" XPath="/MachineInfo/machine"/> </Window.Resources>
3.Xmal设置binding
<DataGrid Name="VMInfo" <span style="color:#ff0000;">DataContext="{Binding Source={StaticResource vminfo}}" ItemsSource="{Binding XPath=/MachineInfo/machine}"</span> AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Machine Name" Binding="{Binding XPath=@name}"/> <DataGridTextColumn Header="OS Version" Binding="{Binding XPath=OS}"/> <DataGridTextColumn Header="IE Version" Binding="{Binding XPath=IE}"/> <DataGridTextColumn Header="Office Version" Binding="{Binding XPath=OFFICE}"/> </DataGrid.Columns> </DataGrid>加 @表示xml元素的属性,不加则表示子级元素
4.运行结果
========== 华丽丽的分割线=========
由于上面的邦定方法不太好对datagrid query,今天又学了一个稍微好点的方法:先把xml读到dataset里,再邦定给datagrid。想要query,对数据源dt进行query就行了。
Xmal设置:
<DataGrid Name="VMInfo" ItemsSource="{Binding}" AutoGenerateColumns="False"> <DataGrid.Columns> <DataGridTextColumn Header="Machine Name" Binding="{Binding XName}"/> <DataGridTextColumn Header="OS Version" Binding="{Binding OS}"/> <DataGridTextColumn Header="IE Version" Binding="{Binding IE}"/> <DataGridTextColumn Header="Office Version" Binding="{Binding OFFICE}"/> </DataGrid.Columns> </DataGrid>
后台设置数据源:
System.Data.DataSet ds = new System.Data.DataSet(); ds.ReadXml(""); System.Data.DataTable dt = ds.Tables[0]; this.VMInfo.Itemssource = dt.DefaultView;