您的位置:首页 > 其它

Binding(五)——使用XML数据作为Binding的源

2012-02-14 13:14 375 查看
先看一个线性集合的例子。下面的XML文本是一组学生的信息存放于D:\RawData.xml,我们要把他显示在一个ListView控件里。

<?xml version="1.0" encoding="utf-8"?>
<StudentList>
<Student Id="1">
<Name>Tim</Name>
</Student>
<Student Id="2">
<Name>Tom</Name>
</Student>
<Student Id="3">
<Name>Vina</Name>
</Student>
<Student Id="4">
<Name>Emily</Name>
</Student>
</StudentList>

程序的XAML部分如下:

<Window x:Class="WpfApplication1.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Title="XML Source" Height="205" Width="240">
<StackPanel Background="LightBlue">
<ListView x:Name="listViewStudents" Height="130" Margin="5">
<ListView.View>
<GridView>
<GridViewColumn Header="Id" Width="80"
DisplayMemberBinding="{Binding XPath=@Id}"/>
<GridViewColumn Header="Name" Width="120"
DisplayMemberBinding="{Binding XPath=Name}"/>
</GridView>
</ListView.View>
</ListView>
<Button Content="Load" Click="Button_Click" Height="25" Margin="5,0"/>
</StackPanel>
</Window>

加粗的两句语句,它们分别为GridView的两列指明了关注的XML的路径。使用@符号加字符串表示的是XML元素的Attribute,不加@符号的字符串表示的是子集元素。
Button的Click事件处理代码如下:

private void Button_Click(object sender, RoutedEventArgs e)
{
XmlDataProvider xdp = new XmlDataProvider();
xdp.Source = new Uri(@"D:\RawData.xml");
xdp.XPath = @"/StudentList/Student";

this.listViewStudents.DataContext = xdp;
this.listViewStudents.SetBinding(ListView.ItemsSourceProperty, new Binding());
}

XmlDataProvider有一个名为Source的属性,可以用它直接指定XML文档所在的位置(无论XML文档存储在本地硬盘还是网络上)。使用XPath选择需要暴露的数据,现在需要一组Student。
运行效果如下:



To be continued...
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息