原文:数据绑定(六)使用XML数据作为Binding的Source
.NET Framework提供了两套处理XML数据的类库
1. 符合DOM标准的类库:包括XmlDocument、XmlElement、XmlNode、XmlAttribute等类,这套类库的特定是中规中矩、功能强大,但也背负了太多XML的传统和复杂
2. 已LINQ为基础的类库:包括XDocument、XElement、XNode、XAttribute等类,这套类库的特点是可以使用LINQ进行查询和操作,方便快捷
xml文件内容如下:
<?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>
界面代码如下:
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="MainWindow" Height="244" Width="412"> <StackPanel Background="LightBlue"> <ListView x:Name="listViewStudents" Height="130" Margin="5"> <ListView.View> <GridView> <GridViewColumn Header="Id" Width="80" DisplayMemberBinding="{Binding [email protected]}" /> <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>
其中,两列分别绑定到XPath上
按钮的点击处理代码如下:
XmlDocument doc = new XmlDocument(); doc.Load("Students.xml"); XmlDataProvider xdp = new XmlDataProvider(); xdp.Document = doc; xdp.XPath = @"/StudentList/Student"; listViewStudents.DataContext = xdp; listViewStudents.SetBinding(ListView.ItemsSourceProperty, new Binding());
代码定义了一个XmlDataProvider对象,使用XmlDataProvider对象读取一个xml文件,可以通过load方法加载一个xml,也可以通过对它的Source属性赋一个Uri来加载一个网络上的xml,例如:
xdp.Source = new Uri(@"d:\Students.xml")
XmlDataProvider对象的XPath属性通过一个XPath指定了所有目标元素的路径
运行效果如图:
xml数据可以作为线性数据的数据源,也可以用于展现树形数据结构,界面代码如下:
<Window x:Class="WpfApplication1.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:WpfApplication1" Title="MainWindow" Height="244" Width="412"> <Window.Resources> <XmlDataProvider x:Key="xdp" XPath="FileSystem/Folder"> <x:XData> <FileSystem xmlns=""> <Folder Name="Books"> <Folder Name="Programming"> <Folder Name="Windows"> <Folder Name="WPF" /> <Folder Name="MFC" /> <Folder Name="Delphi" /> </Folder> </Folder> <Folder Name="Tools"> <Folder Name="Development" /> <Folder Name="Designment" /> <Folder Name="Players" /> </Folder> </Folder> </FileSystem> </x:XData> </XmlDataProvider> </Window.Resources> <Grid> <TreeView ItemsSource="{Binding Source={StaticResource ResourceKey=xdp}}"> <TreeView.ItemTemplate> <HierarchicalDataTemplate ItemsSource="{Binding XPath=Folder}"> <TextBlock Text="{Binding [email protected]}" /> </HierarchicalDataTemplate> </TreeView.ItemTemplate> </TreeView> </Grid> </Window>
运行效果如图:
原文地址:https://www.cnblogs.com/lonelyxmas/p/9080420.html
时间: 2024-11-02 22:33:02