Compartir a través de


Walkthrough: Creating a Data Binding by Using the Silverlight Designer

Microsoft Silverlight will reach end of support after October 2021. Learn more.

This walkthrough shows you how to use the Silverlight Designer for Visual Studio 2010 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.

NoteNote:

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

Prerequisites

You need the following components to complete this walkthrough:

  • Visual Studio 2010.

Creating the Project

The first step is to create the Silverlight 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 Silverlight Application project in Visual Basic or Visual C# named DataBindingDemo. For more information, see How to: Create a New Silverlight Project.

    MainPage.xaml opens in the Silverlight 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.Collections.ObjectModel
    
    ' 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.Collections.ObjectModel;
    
    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. 
    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),
                       New SolidColorBrush(Colors.Green),
                       New SolidColorBrush(Colors.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.Globalization;
    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.
        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 ? 
                        new SolidColorBrush(Colors.Green) : 
                        new SolidColorBrush(Colors.Red);
                }
    
                return b;
            }
    
            // Not used.
            public object ConvertBack(
                object value, 
                Type targetType, 
                object parameter, 
                CultureInfo culture)
            {
                return null;
            }
        }
    }
    
  6. Build the project.

  7. Open MainPage.xaml in the Silverlight Designer.

  8. Replace the automatically generated XAML with the following XAML.

    <UserControl x:Class="DataBindingDemo.MainPage"
      xmlns="https://schemas.microsoft.com/winfx/2006/xaml/presentation"
      xmlns:x="https://schemas.microsoft.com/winfx/2006/xaml"
      xmlns:d="https://schemas.microsoft.com/expression/blend/2008"
      xmlns:mc="https://schemas.openxmlformats.org/markup-compatibility/2006"
      xmlns:local="clr-namespace:DataBindingDemo"
      mc:Ignorable="d"
      d:DesignHeight="300" d:DesignWidth="400">
    
      <UserControl.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>
    
      </UserControl.Resources>
    
      <Grid x:Name="LayoutRoot" Background="White">
    
      </Grid>
    
    </UserControl>
    

Assigning a Data Binding

You use a Binding to display the studentCollection in the ListBox control. The Silverlight 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 design surface.

  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.

    TipTip:

    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 UserControl.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