WPF入门教程系列十七——WPF中的数据绑定(三)

四、 XML数据绑定

     这次我们来学习新的绑定知识,XML数据绑定。XmlDataProvider 用来绑定 XML 数据,该XML数据可以是嵌入.Xmal文件的 XmlDataProvider 标记中,也可以是外部位置引用的文件中。

     当然嵌入式 XML 内容必须置于 XmlDataProvider 内部的 <x:XData> 标记中,而且不容易修改,所以建议使用XML数据文件形式。对于 XmlDataProvider 必须命名一个 x:Key 值,以便数据绑定目标可对其进行引用。

 

      XmlDataProvider 也可以指向 XML 内容的外部源。例如,项目中一个 colors.xml 文件,文件的内容就是一个颜色列表。需要在  <StackPanel.Resources>

中添加一个 XmlDataProvider 资源,并将其的Source设置为 XML 文件名即可。 代码与XML文件如下。

 

<StackPanel>

  <StackPanel.Resources>

                <XmlDataProvider x:Key="MyColors"  Source="Colors.xml"  XPath="colors">

                  

                </XmlDataProvider>

</StackPanel.Resources>

 

XML文件:

 

<?xml version="1.0" encoding="utf-8" ?>

 <colors >

                            <color name="Pink"/>

                            <color name="Red"/>

                            <color name="Purple"/>

                            <color name="Cyan"/>

                            <color name="Gray"/>

                            <color name="Turquoise"/>

       </colors>

 

 

     资源绑定语法与控件绑定语法略有不同。绑定到控件时,可以设置绑定的 ElementName 和 Path 属性。但是绑定到资源时,需要设置 Source 属性,由于我们是绑定到 XmlDataProvider,所以还要设置绑定的 XPath 属性。例如,下列代码可将 ListBox 的项绑定 MyColors资源。将 Source 属性设置为资源,并将其指定为名为 MyColors 的 StaticResource。XPath 属性指示项会绑定到 XML 数据源中 <color> 元素的name属性:

  

<TextBlock Width="248" Height="24" Text="XML数据绑定:"

        TextWrapping="Wrap"/>

            <ListBox x:Name="listXmlColor" Width="248" Height="56" IsSynchronizedWithCurrentItem="True"

                     ItemsSource="{Binding Source={StaticResource MyColors},XPath=color/@name}">

             

            </ListBox>

            <TextBlock Width="248" Height="24" Text="选中的颜色:" />

            <TextBlock Width="248" Height="24" Text="{Binding ElementName=listXmlColor,  Path=SelectedValue, Mode=OneWay}"

                     >

 

            </TextBlock>

 


结果如下图:

 

五、对象绑定和数据模板

     虽然 XmlDataProvider 对 XML 非常有用,但是当您想绑定到对象或对象列表时,可以创建 ObjectDataProvider 作为资源。ObjectDataProvider 的 ObjectType 指定将提供数据绑定源的对象,而 MethodName 则指示为获得数据而需调用的方法。例如,假设我有一个名为 StudentService 的类,该类使用一种名为 GetStudentList的方法来返回列表 <Student>。那么 ObjectDataProvider 应该如下所示:

<StackPanel.Resources>

     <ObjectDataProvider x:Key="students"  ObjectType="{x:Type local:StudentService}" MethodName="GetStudentList">

 

                </ObjectDataProvider>

</StackPanel.Resources>

 

     ObjectDataProvider 还可以使用许多其他属性。ConstructionParameters 属性允许您将参数传递给要调用的类的构造函数。此外,可以使用 MethodParameters 属性来指定参数,同时还可以使用 ObjectInstance 属性来指定现有的对象实例作为源。

如果希望异步检索数据,可以将 ObjectDataProvider 的 IsAsynchronous 属性设为 true。这样,用户将可以在等待数据填充绑定到 ObjectDataProvider 的源的目标控件时与屏幕进行交互。

      在添加 ObjectDataProvider 时,必须限定数据源类的命名空间。在本例中,我必须将 xmlns 属性添加到 <Window> 标记中,以便 local 快捷方式符合要求,并指示正确的命名空间:

xmlns:local="clr-namespace:WpfApp1.Services"

      既然数据源已通过 ObjectDataProvider 定义,接下来就是如何将数据显示在 ListBox 控件。我要把姓名、年龄、出生日期、国籍在每个 ListBoxItem 中一行显示。姓名用粗体,年龄、出生日期、国籍使用默认字体显示。这在 XAML 中,通过使用数据模板(DataTemplate)很容易实现的,DataTemplate 允许您定义自己的显示样式。

      如下代码,在XAML代码中我将 DataTemplate 定义成如何显示Student信息的布局样式。我通过设置 DataTemplate 的 DataType 属性为students,告诉 DataTemplate 将要引用 Student类型。

      我将对象数据students绑定到 ListBox 的 ItemsSource 属性,这样就把将数据绑定到 ListBox了,但是我没有指定如何显示绑定的数据,显示样式是通过将 ItemTemplate 属性设置为 studentLayout资源(即 DataTemplate 的键名),就可以根据我之前在模板中设计的显示样式显示数据了。最终结果如下图 所示。

 

XMAL代码:

        <StackPanel Grid.Row="3">

            <StackPanel.Resources>

                <ObjectDataProvider x:Key="students"  ObjectType="{x:Type local:StudentService}" MethodName="GetStudentList">

 

                </ObjectDataProvider>

 

                <DataTemplate x:Key="studentLayout" DataType="students">

                    <StackPanel Orientation="Horizontal">

                        <TextBlock Text="{Binding Path=Name}"

                            FontWeight="Bold" Foreground="Blue"/>

                        <TextBlock Text=", "></TextBlock>

                        <TextBlock Text="{Binding Path=Age}"></TextBlock>

                            <TextBlock Text=", "></TextBlock>

                            <TextBlock Text="{Binding Path=Birthday}"></TextBlock>

                              <TextBlock Text=", "></TextBlock>

                            <TextBlock Text="{Binding Path=Country}"></TextBlock>

                 

                    </StackPanel>

                </DataTemplate>

 

            </StackPanel.Resources>

            <TextBlock Width="248" Height="24" Text="对象数据绑定:"

        TextWrapping="Wrap"/>

            <ListBox x:Name="listObjectBind" Width="450" Height="100" IsSynchronizedWithCurrentItem="True"

                     ItemsSource="{Binding Source={StaticResource students}}"

                     ItemTemplate="{DynamicResource studentLayout}">

 

            </ListBox>

       </StackPanel>

 

c#代码如下:

 

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WpfApp1.Models;

namespace WpfApp1.Services
{
   public class StudentService
    {
       public List<Student> GetStudentList()
       {
           Student liang = new Student();
           liang.Age = "18";
           liang.Name = "梁丘";
           liang.Birthday = "1990-02-03";
           liang.Country = "中国";
           Student zuo = new Student();
           zuo.Age = "22";
           zuo.Name = "左丘";
           zuo.Birthday = "1992-02-03";
           zuo.Country = "中国";
           Student diwu = new Student();
           diwu.Age = "32";
           diwu.Name = "第五言";
           diwu.Birthday = "1982-11-03";
           diwu.Country = "中国";
           Student yang = new Student();
           yang.Age = "12";
           yang.Name = "羊舌微";
           yang.Birthday = "2002-11-13";
           yang.Country = "中国";
           List<Student> personList = new List<Student>();
           personList.Add(liang);
           personList.Add(zuo);
           personList.Add(diwu);
           personList.Add(yang);
           return personList;
       }

    }
}

 

 

 

posted @ 2015-08-18 15:20  DotNet菜园  阅读(23789)  评论(8编辑  收藏  举报