Поделиться через


Walkthrough: Creating a Data Binding by Using the WPF Designer

This walkthrough shows you how to use the WPF Designer for Visual Studio to create data bindings that connect data to a control. 

In this walkthrough, you perform the following tasks:

  • Create the project.

  • Create a Student class and a StudentList collection.

  • Create a ListBox control that displays the StudentList collection through a data binding.

  • Create a custom DataTemplate which uses an IValueConverter to customize the appearance of a Boolean property.

When you are finished, you will have a list box that is bound to a list of students. For each list box item, a colored square is displayed that indicates whether the student is currently enrolled.

Note

To bind to data from a data connection, use the Data Sources window. For more information, see Binding WPF Controls to Data in Visual Studio.

Note

The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, choose Import and Export Settings on the Tools menu. For more information, see Working with Settings.

Prerequisites

You need the following components to complete this walkthrough:

  • Visual Studio 2010.

Creating the Project

The first step is to create the WPF Application project and add the data source. The data source is an ObservableCollection<T> that contains instances of a simple Student class. The project also has an IValueConverter and a custom DataTemplate to style the ListBox control.

To create the project

  1. Create a new WPF Application project in Visual Basic or Visual C# named DataBindingDemo. For more information, see How to: Create a New WPF Application Project.

    MainWindow.xaml opens in the WPF Designer.

  2. Add a new class named Student to the project. For more information, see How to: Add New Project Items.

  3. Replace the automatically generated code with the following code.

    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. Add a new class named BoolToBrushConverter to the project.

  5. Replace the automatically generated code with the following code.

    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. Build the project.

  7. Open MainWindow.xaml in the WPF Designer.

  8. Replace the automatically generated XAML with the following 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>
    

Assigning a Data Binding

You use a Binding to display the studentCollection in the ListBox control. The WPF Designer enables data binding without writing any code or XAML.

To bind the ListBox to the data source

  1. From the Toolbox, drag a ListBox control onto the Window.

  2. In the Properties window, scroll to the ItemsSource property.

  3. At the edge of the left column, click the property marker (property marker).

    A menu appears.

    Tip

    You can also right-click the row to display the menu.

  4. Click Apply Data Binding.

    The data binding builder appears.

    data binding builder

  5. On the Source pane, in the left panel, click StaticResource.

  6. In the middle panel, click Window.Resources.

  7. In the right panel, click studentCollection.

    The ListBox control is populated with items.

  8. In the Properties window, scroll to the DisplayMemberPath property and set its value to StudentName.

    The ListBox control displays the StudentName property for each Student instance in studentCollection.

    ListBox data binding

Creating a Data Binding with a Value Converter

You create a DataTemplate to format your data in the ListBox control. In this project, the DataTemplate uses a value converter to display a Boolean property as a colored square.

To create a data binding with a value converter

  1. In the Properties window, clear the DisplayMemberPath property.

  2. Scroll to the ItemTemplate property.

  3. Click the property marker (property marker).

  4. Click Apply Resource.

    The resource picker appears.

  5. In the Local section, click listBoxTemplate.

    The ListBox control displays a red or green square next to each student name that indicates whether the student is enrolled.

    ListBox data binding with a value converter

Next Steps

See Also

Reference

Binding

ListBox

ItemTemplate

IValueConverter

Concepts

Data Binding Overview

Other Resources

Working with the WPF Designer