深入浅出WPF 第二部分(6)

本文详细介绍了如何使用XML数据作为WPF ListView控件的数据源,并通过XPath表达式实现复杂的数据绑定,包括如何加载XML文件,使用XMLDataProvider类设置数据源及XPath路径,以及如何在ListView中显示XML数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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,不加@符号的字符串表示的是子级元素。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值