6.3.9 使用XML数据作为Binding的源
现代程序设计只要涉及数据传输就离不开XML,因为大多数数据传输都是基于SOAP相关的协议,而SOAP又是通过将对象序列化为XML文本进行传输。XML文本是树形结构的,所以XML可以方便地用于表示线性集合和树形数据结构。
<ListView x:Name="listViewStudents" Height="130" Margin="5">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" Width="60" DisplayMemberBinding="{Binding XPath=@Id}"/>
<GridViewColumn Header="Name" Width="80" DisplayMemberBinding="{Binding XPath=Name}"/>
<GridViewColumn Header="Age" Width="60" DisplayMemberBinding="{Binding XPath=Age}"/>
</GridView>
</ListView.View>
</ListView>
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(@"C:\Users\v-xufeif\Desktop\Students.xml");
XmlDataProvider xdp = new XmlDataProvider()
{
Document = xmlDoc,
XPath = @"/StudentList/Student"
};
this.listViewStudents.DataContext = xdp;
this.listViewStudents.SetBinding(ListView.ItemsSourceProperty, new Binding());
XMLDataProvider还有一个名为Source的属性,可以用它直接指定XML文档所在的位置。
XmlDataProvider xdp = new XmlDataProvider()
{
Source = new Uri(@"C:\Users\v-xufeif\Desktop\Students.xml"),
XPath = @"/StudentList/Student"
};
this.listViewStudents.DataContext = xdp;
this.listViewStudents.SetBinding(ListView.ItemsSourceProperty, new Binding());
使用@符号加字符串表示的是XML元素的Attribute,不加@符号的字符串表示的是子级元素。