演练:使用 WPF 设计器创建数据绑定

本演练演示如何使用适用于 Visual Studio 的 WPF 设计器创建将数据连接到控件的数据绑定。 

在本演练中,您将执行下列任务:

  • 创建项目。

  • 创建一个 Student 类和一个 StudentList 集合。

  • 创建一个通过数据绑定显示 StudentList 集合的 ListBox 控件。

  • 创建一个使用 IValueConverter 自定义布尔属性外观的自定义 DataTemplate

在完成后,将拥有一个绑定到学生列表的列表框。 对于每个列表框项目,都会显示一个彩色正方形来指示学生当前是否已注册。

提示

若要通过数据连接与数据绑定,请使用“数据源”窗口。 有关更多信息,请参见在 Visual Studio 中将 WPF 控件绑定到数据

提示

显示的对话框和菜单命令可能会与“帮助”中的描述不同,具体取决于您现用的设置或版本。 若要更改设置,请在“工具”菜单上选择“导入和导出设置”。 有关更多信息,请参见 使用设置

系统必备

您需要以下组件来完成本演练:

  • Visual Studio 2010.

创建项目

第一步是创建 WPF 应用程序项目并添加数据源。 数据源是一个包含简单 Student 类的实例的 ObservableCollection<T>。 该项目还具有一个 IValueConverter 和一个用来设置 ListBox 控件样式的自定义 DataTemplate

创建项目

  1. 使用 Visual Basic 或 Visual C# 新建一个名为 DataBindingDemo 的 WPF 应用程序项目。 有关更多信息,请参见如何:创建新的 WPF 应用程序项目

    MainWindow.xaml 将在 WPF 设计器中打开。

  2. 将名为 Student 的新类添加到项目中。 有关更多信息,请参见如何:添加新项目项

  3. 用下面的代码替换自动生成的代码。

    Imports System
    Imports System.Collections.ObjectModel
    Imports System.Windows
    
    ' Student is a simple class that stores a name and an 
    ' IsEnrolled value. 
    Public Class Student
    
        ' The default constructor is required for creation from XAML. 
        Public Sub New()
        End Sub
    
        ' The StudentName property is a string that holds the first and last name. 
        Public Property StudentName As String
    
        ' The IsEnrolled property gets or sets a value indicating whether 
        ' the student is currently enrolled. 
        Public Property IsEnrolled As Boolean
    
    End Class
    
    ' The StudentList collection is declared for convenience, 
    ' because declaring generic types in XAML is inconvenient. 
    Public Class StudentList
        Inherits ObservableCollection(Of Student)
    End Class
    
    using System;
    using System.Collections.ObjectModel;
    using System.Windows;
    
    namespace DataBindingDemo
    {
        // Student is a simple class that stores a name and an
        // IsEnrolled value.
        public class Student 
        {   
            // The default constructor is required for creation from XAML.
            public Student()
            {
            }
    
            // The StudentName property is a string that holds the first and last name.
            public string StudentName { get; set; }
    
            // The IsEnrolled property gets or sets a value indicating whether
            // the student is currently enrolled.
            public bool IsEnrolled { get; set; }
        }
    
        // The StudentList collection is declared for convenience,
        // because declaring generic types in XAML is inconvenient.
        public class StudentList : ObservableCollection<Student>
        {
    
        }
    }
    
  4. 将名为 BoolToBrushConverter 的新类添加到项目中。

  5. 用下面的代码替换自动生成的代码。

    Imports System
    Imports System.Globalization
    Imports System.Windows.Data
    Imports System.Windows.Media
    
    ' The BoolToBrushConverter class is a value converter 
    ' that helps to bind a bool value to a brush property. 
    <ValueConversion(GetType(Boolean), GetType(Brush))> _
    Public Class BoolToBrushConverter
        Implements IValueConverter
    
        Public Function Convert( _
            ByVal value As Object, _
            ByVal targetType As Type, _
            ByVal parameter As Object, _
            ByVal culture As CultureInfo) As Object Implements IValueConverter.Convert
    
            Dim b As Brush = Nothing
    
            ' Only apply the conversion if value is assigned and 
            ' is of type bool. 
            If value IsNot Nothing AndAlso value.[GetType]() Is GetType(Boolean) Then
                ' true is painted with a green brush, 
                ' false with a red brush. 
                b = If(CBool(value), Brushes.Green, Brushes.Red)
            End If
    
            Return b
        End Function
    
        ' Not used. 
        Public Function ConvertBack( _
            ByVal value As Object, _
            ByVal targetType As Type, _
            ByVal parameter As Object, _
            ByVal culture As CultureInfo) As Object Implements IValueConverter.ConvertBack
            Return Nothing
        End Function
    
    End Class
    
    using System;
    using System.Collections.Generic;
    using System.Globalization;
    using System.Linq;
    using System.Text;
    using System.Windows.Data;
    using System.Windows.Media;
    
    namespace DataBindingDemo
    {
        // The BoolToBrushConverter class is a value converter
        // that helps to bind a bool value to a brush property.
        [ValueConversion(typeof(bool), typeof(Brush))]
        public class BoolToBrushConverter : IValueConverter
        {
            public object Convert(
                object value, 
                Type targetType, 
                object parameter, 
                CultureInfo culture)
            {
                Brush b = null;
    
                // Only apply the conversion if value is assigned and
                // is of type bool.
                if (value != null &&
                    value.GetType() == typeof(bool))
                {
                    // true is painted with a green brush, 
                    // false with a red brush.
                    b = (bool)value ? Brushes.Green : Brushes.Red;
                }
    
                return b;
            }
    
            // Not used.
            public object ConvertBack(
                object value, 
                Type targetType, 
                object parameter, 
                CultureInfo culture)
            {
                return null;
            }
        }
    }
    
  6. 生成项目。

  7. 在 WPF 设计器中打开 MainWindow.xaml。

  8. 用下面的 XAML 替换自动生成的 XAML。

        <Window x:Class="DataBindingDemo.MainWindow"
            xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
            xmlns:local="clr-namespace:DataBindingDemo"
            Title="Databinding Demo" Height="300" Width="300">
        <Window.Resources>
    
            <local:StudentList x:Key="studentCollection" >
                <local:Student StudentName="Syed Abbas" IsEnrolled="false" />
                <local:Student StudentName="Lori Kane" IsEnrolled="true" />
                <local:Student StudentName="Steve Masters" IsEnrolled="false" />
                <local:Student StudentName="Tai Yee" IsEnrolled="true" />
                <local:Student StudentName="Brenda Diaz" IsEnrolled="true" />
            </local:StudentList>
    
            <local:BoolToBrushConverter x:Key="boolToBrushConverter" />
    
            <DataTemplate x:Key="listBoxTemplate">
                <StackPanel Orientation="Horizontal" >
                    <Rectangle Fill="{Binding Path=IsEnrolled, Converter={StaticResource boolToBrushConverter}}"
                               Height="10" 
                               Width="10" 
                               Margin="0,0,5,0" />
                    <TextBlock Text="{Binding Path=StudentName}" />
                </StackPanel>
            </DataTemplate>
    
        </Window.Resources>
        <Grid></Grid>
    
    </Window>
    

分配数据绑定

可以使用 Binding 来显示 ListBox 控件中的 studentCollection。 使用 WPF 设计器可以在不编写任何代码或 XAML 的情况下实现数据绑定。

将 ListBox 绑定到数据源

  1. 将一个 ListBox 控件从**“工具箱”**拖到 Window 上。

  2. 在“属性”窗口中,滚动到 ItemsSource 属性。

  3. 在左列的边缘,单击**“属性标记”**(属性标记)。

    此时出现一个菜单。

    提示

    您还可以右击该行以显示菜单。

  4. 单击**“应用数据绑定”**。

    将显示数据绑定生成器。

    数据绑定生成器

  5. 在**“源”窗格上的左面板中,单击“StaticResource”**。

  6. 在中间面板中,单击**“Window.Resources”**。

  7. 在右侧面板中,单击**“studentCollection”**。

    ListBox 控件用相应的项填充。

  8. 在“属性”窗口中,滚动到 DisplayMemberPath 属性并将它的值设置为 StudentName。

    ListBox 控件显示 studentCollection 中每个 Student 实例的 StudentName 属性。

    ListBox 数据绑定

使用值转换器创建数据绑定

可以创建一个用来设置 ListBox 控件中数据格式的 DataTemplate。 在此项目中,DataTemplate 使用值转换器将布尔属性显示为彩色正方形。

使用值转换器创建数据绑定

  1. 在“属性”窗口中,清除 DisplayMemberPath 属性。

  2. 滚动到 ItemTemplate 属性。

  3. 单击**“属性标记”**(属性标记)。

  4. 单击**“应用资源”**。

    此时出现资源选取器。

  5. 在**“本地”**部分中,请单击 listBoxTemplate

    ListBox 控件会在每个学生姓名旁边显示一个红色或绿色正方形来指示学生是否已注册。

    带值转换器的 ListBox 数据绑定

后续步骤

请参见

参考

Binding

ListBox

ItemTemplate

IValueConverter

概念

数据绑定概述

其他资源

使用 WPF 设计器