Share via


연습: WPF Designer를 사용하여 데이터 바인딩 만들기

이 연습에서는 WPF Designer for Visual Studio를 사용하여 데이터를 컨트롤에 연결하는 데이터 바인딩을 만드는 방법을 보여 줍니다. 

이 연습에서는 다음 작업을 수행합니다.

  • 프로젝트를 만듭니다.

  • Student 클래스 및 StudentList 컬렉션을 만듭니다.

  • 데이터 바인딩을 통해 StudentList 컬렉션을 표시하는 ListBox 컨트롤을 만듭니다.

  • IValueConverter를 사용하여 부울 속성의 모양을 사용자 지정하는 사용자 지정 DataTemplate을 만듭니다.

연습을 마치면 학생 목록에 바인딩된 목록 상자가 완성됩니다. 목록 상자의 각 항목에 대해 학생이 현재 등록되어 있는지 여부를 나타내는 색칠된 사각형이 표시됩니다.

참고

데이터 연결을 통해 데이터에 바인딩하려면 데이터 소스 창을 사용합니다. 자세한 내용은 Visual Studio에서 데이터에 WPF 컨트롤 바인딩을 참조하십시오.

참고

표시되는 대화 상자와 메뉴 명령은 활성 설정이나 버전에 따라 도움말에서 설명하는 것과 다를 수 있습니다. 설정을 변경하려면 도구 메뉴에서 설정 가져오기 및 내보내기를 선택합니다. 자세한 내용은 설정에 대한 작업을 참조하십시오.

사전 요구 사항

이 연습을 완료하려면 다음 구성 요소가 필요합니다.

  • Visual Studio 2010.

프로젝트 만들기

첫 번째 단계로 WPF 응용 프로그램 프로젝트를 만들고 데이터 소스를 추가합니다. 데이터 소스는 단순한 Student 클래스의 인스턴스가 들어 있는 ObservableCollection<T>입니다. 또한 이 프로젝트에는 IValueConverterListBox 컨트롤의 스타일을 지정하기 위한 DataTemplate이 들어 있습니다.

프로젝트를 만들려면

  1. Visual Basic 또는 Visual C#에서 DataBindingDemo라는 새 WPF 응용 프로그램 프로젝트를 만듭니다. 자세한 내용은 방법: 새 WPF 응용 프로그램 프로젝트 만들기를 참조하십시오.

    WPF Designer에 MainWindow.xaml이 열립니다.

  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 Designer에서 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 Designer를 사용하면 코드나 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 데이터 바인딩

값 변환기를 사용하여 데이터 바인딩 만들기

DataTemplate을 만들어 ListBox 컨트롤의 데이터에 서식을 지정할 수 있습니다. 이 프로젝트에서는 DataTemplate이 값 변환기를 사용하여 부울 속성을 색칠된 사각형으로 표시합니다.

값 변환기를 사용하여 데이터 바인딩을 만들려면

  1. 속성 창에서 DisplayMemberPath 속성을 지웁니다.

  2. ItemTemplate 속성으로 스크롤합니다.

  3. 속성 표식 (속성 마커)을 클릭합니다.

  4. 리소스 적용을 클릭합니다.

    리소스 선택기가 나타납니다.

  5. 로컬 섹션에서 listBoxTemplate을 클릭합니다.

    ListBox 컨트롤의 각 학생 이름 옆에 학생이 등록되었는지 여부를 나타내는 빨강 또는 녹색 사각형이 표시됩니다.

    값 변환기가 있는 ListBox 데이터 바인딩

다음 단계

참고 항목

참조

Binding

ListBox

ItemTemplate

IValueConverter

개념

데이터 바인딩 개요

기타 리소스

WPF 디자이너 작업