Share via


연습: 개체에 Silverlight 컨트롤 바인딩

이 연습에서는 데이터 바인딩된 컨트롤이 포함된 Silverlight 응용 프로그램을 만듭니다. 이 컨트롤은 관련된 사용자 정의 비즈니스 개체 2개에 바인딩됩니다.

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

  • Silverlight 응용 프로그램 만들기

  • 사용자 인터페이스에 바인딩할 관련된 사용자 지정 개체 2개 만들기

  • 데이터 소스 구성 마법사를 실행하여 데이터 소스 창을 채우는 사용자 지정 개체에 연결

  • 데이터 소스 창에서 Silverlight Designer로 항목을 끌어 데이터 바인딩된 컨트롤 집합 만들기

    참고

    컴퓨터에서 일부 Visual Studio 사용자 인터페이스 요소에 대해 다음 지침에서 설명한 것과는 다른 이름이나 위치를 표시할 수 있습니다. 설치한 Visual Studio 버전과 사용하는 설정에 따라 이러한 요소가 결정됩니다. 자세한 내용은 설정에 대한 작업을 참조하십시오.

사전 요구 사항

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

  • Visual Studio 2010.

연습을 완료하려면 다음 개념에 대한 사전 지식이 유용하지만 반드시 필요하지는 않습니다.

  • Silverlight Designer 작업. 자세한 내용은 Silverlight를 참조하십시오.

  • Silverlight 데이터 바인딩. 자세한 내용은 데이터 바인딩을 참조하십시오.

  • XAML 작업. 자세한 내용은 XAML을 참조하십시오.

Silverlight 응용 프로그램 만들기

이 연습의 시작 단계로 Silverlight 응용 프로그램을 만듭니다.

Silverlight 프로젝트를 만들려면

  1. 파일 메뉴에서 새 프로젝트를 만듭니다.

  2. Visual C# 또는 Visual Basic 노드 아래에서 Silverlight, Silverlight 응용 프로그램을 차례로 클릭합니다.

  3. 이름 상자에 SilverlightObjectBinding을 입력한 다음 확인을 클릭합니다.

  4. 새 Silverlight 응용 프로그램 대화 상자에서 기본 설정을 그대로 두고 확인을 클릭합니다.

    이 Silverlight 응용 프로그램은 프로젝트가 2개인 솔루션으로 만들어집니다. 두 프로젝트는 SilverlightObjectBinding 프로젝트를 호스팅하는 데 사용되는 SilverlightObjectBinding.Web 프로젝트와 SilverlightObjectBinding 프로젝트입니다.

바인딩할 사용자 지정 개체 만들기

응용 프로그램에 데이터를 노출하려면 데이터 모델이 정의되어야 합니다. 이 연습에서는 데이터 모델을 위해 고객 및 주문을 나타내는 사용자 지정 개체를 만듭니다.

Customers 개체를 만들려면

  1. 솔루션 탐색기에서 SilverlightObjectBinding 프로젝트를 마우스 오른쪽 단추로 클릭하고 추가를 가리킨 다음 새 항목을 클릭합니다.

  2. 새 항목 추가 대화 상자에서 클래스 항목을 클릭합니다.

  3. 이름을 Customer로 바꾸고 추가를 클릭합니다.

  4. Customer 코드 파일에서 Customer 클래스를 다음 코드로 바꿉니다.

    ''' <summary>
    ''' A single customer
    ''' </summary>
    Public Class Customer
    
        Public Sub New()
        End Sub
    
        ''' <summary>
        ''' Creates a new customer
        ''' </summary>
        ''' <param name="customerId">The ID that uniquely identifies this customer</param>
        ''' <param name="companyName">The name for this customer</param>
        ''' <param name="city">The city for this customer</param>
        Public Sub New(ByVal customerId As String,
                       ByVal companyName As String,
                       ByVal city As String)
            customerIDValue = customerId
            companyNameValue = companyName
            cityValue = city
        End Sub
    
        Private customerIDValue As String
        ''' <summary>
        ''' The ID that uniquely identifies this customer
        ''' </summary>
        Public Property CustomerID() As String
            Get
                Return customerIDValue
            End Get
            Set(ByVal value As String)
                customerIDValue = value
            End Set
        End Property
    
        Private companyNameValue As String
        ''' <summary>
        ''' The name for this customer
        ''' </summary>
        Public Property CompanyName() As String
            Get
                Return companyNameValue
            End Get
            Set(ByVal Value As String)
                companyNameValue = Value
            End Set
        End Property
    
        Private cityValue As String
        ''' <summary>
        ''' The city for this customer
        ''' </summary>
        Public Property City() As String
            Get
                Return cityValue
            End Get
            Set(ByVal Value As String)
                cityValue = Value
            End Set
        End Property
    
        Private ordersValue As Orders
        ''' <summary>
        ''' The orders for this customer
        ''' </summary>
        Public Property Orders As Orders
            Get
                Return ordersValue
            End Get
            Set(ByVal value As Orders)
                ordersValue = value
            End Set
        End Property
    
    
        Public Overrides Function ToString() As String
            Return Me.CompanyName & " (" & Me.CustomerID & ")"
        End Function
    End Class
    
    
    ''' <summary>
    ''' A collection of Customer objects.
    ''' </summary>
    ''' <remarks></remarks>
    Public Class Customers
        Inherits System.Collections.Generic.List(Of Customer)
    
    End Class
    
    /// <summary>
    /// A single customer
    /// </summary>
    public class Customer
    {
        /// <summary>
        /// Creates a new customer
        /// </summary>
        public Customer()
        {
        }
    
        /// <summary>
        /// Creates a new customer
        /// </summary>
        /// <param name="customerID"></param>
        /// <param name="companyName"></param>
        /// <param name="city"></param>
        public Customer(string customerID, string companyName,
           string city)
        {
            customerIDValue = customerID;
            companyNameValue = companyName;
            cityValue = city;
        }
    
        private string customerIDValue;
        /// <summary>
        /// The ID that uniquely identifies this customer
        /// </summary>
        public string CustomerID
        {
            get { return customerIDValue; }
            set { customerIDValue = value; }
        }
    
        private string companyNameValue;
        /// <summary>
        /// The name for this customer
        /// </summary>
        public string CompanyName
        {
            get { return companyNameValue; }
            set { companyNameValue = value; }
        }
    
        private string cityValue;
        /// <summary>
        /// The city for this customer
        /// </summary>
        public string City
        {
            get { return cityValue; }
            set { cityValue = value; }
        }
    
        private Orders ordersValue;
        /// <summary>
        /// The orders for this customer
        /// </summary>
        public Orders Orders
        {
            get { return ordersValue; }
            set { ordersValue = value; }
        }
    
        public override string ToString()
        {
            return this.CompanyName + " (" + this.CustomerID + ")";
        }
    }
    
    /// <summary>
    /// A collection of Customer objects
    /// </summary>
    public class Customers : System.Collections.Generic.List<Customer>
    {
    
    }
    

Orders 개체를 만들려면

  1. 솔루션 탐색기에서 SilverlightObjectBinding 프로젝트를 마우스 오른쪽 단추로 클릭하고 추가를 가리킨 다음 새 항목을 클릭합니다.

  2. 새 항목 추가 대화 상자에서 클래스 항목을 클릭합니다.

  3. 이름을 Order로 바꾸고 추가를 클릭합니다.

  4. Order 코드 파일에서 Order 클래스를 다음 코드로 바꿉니다.

    ''' <summary>
    ''' A single order
    ''' </summary>
    Public Class Order
    
        Public Sub New()
        End Sub
    
        ''' <summary>
        ''' Creates a new order
        ''' </summary>
        ''' <param name="orderid">The identifier for this order</param>
        ''' <param name="customerID">The customer who placed this order</param>
        Public Sub New(ByVal orderid As Integer,
                       ByVal customerID As String)
            orderIDValue = orderid
            customerIDValue = customerID
        End Sub
    
        Private orderIDValue As Integer
        ''' <summary>
        ''' Identifier for this order
        ''' </summary>
        Public Property OrderID() As Integer
            Get
                Return orderIDValue
            End Get
            Set(ByVal value As Integer)
                orderIDValue = value
            End Set
        End Property
    
        Private customerIDValue As String
        ''' <summary>
        ''' The customer who placed this order
        ''' </summary>
        Public Property CustomerID() As String
            Get
                Return customerIDValue
            End Get
            Set(ByVal Value As String)
                customerIDValue = Value
            End Set
        End Property
    End Class
    
    ''' <summary>
    ''' A collection of Orders
    ''' </summary>
    Public Class Orders
        Inherits System.Collections.Generic.List(Of Order)
    
    End Class
    
    /// <summary>
    /// A single order
    /// </summary>
    public class Order
    {
        /// <summary>
        /// Creates a new order
        /// </summary>
        /// <param name="orderid"></param>
        /// <param name="customerID"></param>
        public Order(int orderid, string customerID)
        {
            orderIDValue = orderid;
            customerIDValue = customerID;
        }
    
        private int orderIDValue;
        /// <summary>
        /// The ID that uniquely identifies this order
        /// </summary>
        public int OrderID
        {
            get { return orderIDValue; }
            set { orderIDValue = value; }
        }
    
        private string customerIDValue;
        /// <summary>
        /// The customer who placed this order
        /// </summary>
        public string CustomerID
        {
            get { return customerIDValue; }
            set { customerIDValue = value; }
        }
    }
    
    /// <summary>
    /// A collection of Order objects
    /// </summary>
    public class Orders : System.Collections.Generic.List<Order>
    {
    
    }
    
  5. 프로젝트를 빌드합니다.

개체 데이터 소스 만들기

데이터 소스 구성 마법사를 실행하여 개체 데이터 소스를 만들고 데이터 소스 창을 채웁니다.

개체 데이터 소스를 만들려면

  1. 데이터 메뉴에서 데이터 소스 표시를 클릭합니다.

  2. 데이터 소스 창에서 새 데이터 소스 추가를 클릭합니다.

    데이터 소스 구성 마법사가 나타납니다.

  3. 데이터 소스 형식 선택 페이지에서 개체를 클릭한 후 다음을 클릭합니다.

  4. 데이터 개체 선택 페이지에서 트리 뷰를 두 번 확장한 다음 Customers 옆에 있는 확인란을 선택합니다.

    참고

    단일 Customer가 아니라 Customers를 선택해야 합니다. Customers가 나타나지 않으면 마법사를 종료하고 솔루션을 다시 빌드합니다.

  5. 마침을 클릭합니다.

    데이터 소스 창이 개체 데이터 소스로 채워집니다.

데이터 바인딩된 컨트롤 만들기

데이터 소스 창에서 디자이너로 CustomersOrders 노드를 끌어 개체의 표시를 표시하는 컨트롤을 만듭니다.

데이터 바인딩된 컨트롤을 만들려면

  1. 디자인 뷰에서 MainPage.xaml을 엽니다.

  2. Customers 노드를 데이터 소스 창에서 디자이너로 끌어 옵니다.

  3. 데이터 소스 창에서 디자이너의 고객 표 아래로 Orders 노드를 끕니다.

개체를 데이터로 채우고 생성된 CollectionViewSource에 개체 바인딩

이 연습에서는 사용자 지정 개체를 데이터 모델로 사용하기 때문에 샘플 데이터는 Silverlight 페이지가 열릴 때 만들어져 로드됩니다.

데이터 소스 창에서 개체 데이터 소스를 끌어 오면 데이터 소스가 사용자 지정 개체를 가리키도록 구성하는 데 도움이 되는 코드 주석이 생성됩니다. 생성된 코드의 주석 처리를 제거하고 [System.Windows.Data.CollectionViewSource.Source](myCollectionViewSource)가 사용자 지정 데이터 개체 컬렉션을 가리키도록 설정합니다. 다음 절차에서는 생성된 코드를 생성된 컨트롤에 바인딩하기 위해 해당 코드를 수정하는 방법을 보여 줍니다.

데이터 소스 창에서 디자이너로 항목을 끌어 올 때마다 Silverlight 페이지에서 [System.Windows.Data.CollectionViewSource]가 생성됩니다. 이름은 사용 중인 데이터 소스에 따라 결정됩니다. 사용 중인 언어에 따라 'Resource Key for CollectionViewSource' 주석을 CustomersViewSource 또는 customerViewSource로 바꿉니다.

개체를 데이터로 채우고 컨트롤을 개체에 바인딩하려면

  1. 솔루션 탐색기에서 MainPage.xaml 노드를 확장한 다음 MainPage.xaml 코드 파일을 두 번 클릭합니다.

  2. 코드 파일(MainPage.xaml.vb 또는 MainPage.xaml.cs)에서 다음 메서드를 MainPage 클래스에 추가합니다.

    ' Create sample data.
    Private Function GetCustomers() As Customers
    
        Dim customers As New Customers
    
        ' Create 3 sample customers,
        ' each with 3 sample orders.
        Dim cust1 As New Customer("1", "A Bike Store", "Seattle")
        Dim cust1Orders As New Orders
        cust1Orders.Add(New Order(1, cust1.CustomerID))
        cust1Orders.Add(New Order(2, cust1.CustomerID))
        cust1Orders.Add(New Order(3, cust1.CustomerID))
        cust1.Orders = cust1Orders
    
        Dim cust2 As New Customer("2", "Progressive Sports", "Renton")
        Dim cust2Orders As New Orders
        cust2Orders.Add(New Order(4, cust2.CustomerID))
        cust2Orders.Add(New Order(5, cust2.CustomerID))
        cust2Orders.Add(New Order(6, cust2.CustomerID))
        cust2.Orders = cust2Orders
    
        Dim cust3 As New Customer("3", "Advanced Bike Components", "Irving")
        Dim cust3Orders As New Orders
        cust3Orders.Add(New Order(7, cust3.CustomerID))
        cust3Orders.Add(New Order(8, cust3.CustomerID))
        cust3Orders.Add(New Order(9, cust3.CustomerID))
        cust3.Orders = cust3Orders
    
        ' Add the sample customer objects to the 
        ' Customers collection.
        customers.Add(cust1)
        customers.Add(cust2)
        customers.Add(cust3)
    
        Return customers
    End Function
    
    // Create sample data.
    private Customers GetCustomers()
    {
        Customers customers = new Customers();
    
        // Create 3 sample customers,
        // each with 3 sample orders.
        Customer cust1 = new Customer("1", "A Bike Store", "Seattle");
        Orders cust1Orders = new Orders();
        cust1Orders.Add(new Order(1, cust1.CustomerID));
        cust1Orders.Add(new Order(2, cust1.CustomerID));
        cust1Orders.Add(new Order(3, cust1.CustomerID));
        cust1.Orders = cust1Orders;
    
        Customer cust2 = new Customer("2", "Progressive Sports", "Renton");
        Orders cust2Orders = new Orders();
        cust2Orders.Add(new Order(4, cust2.CustomerID));
        cust2Orders.Add(new Order(5, cust2.CustomerID));
        cust2Orders.Add(new Order(6, cust2.CustomerID));
        cust2.Orders = cust2Orders;
    
        Customer cust3 = new Customer("3", "Advanced Bike Components", "Irving");
        Orders cust3Orders = new Orders();
        cust3Orders.Add(new Order(7, cust3.CustomerID));
        cust3Orders.Add(new Order(8, cust3.CustomerID));
        cust3Orders.Add(new Order(9, cust3.CustomerID));
        cust3.Orders = cust3Orders;
    
        // Add the sample customer objects to the 
        // Customers collection.
        customers.Add(cust1);
        customers.Add(cust2);
        customers.Add(cust3);
    
        return customers;
    }
    
  3. UserControl_Loaded 이벤트 처리기 내의 주석 처리된 코드를 다음과 같이 바꿉니다.

    Private Sub UserControl_Loaded(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
    
        'Do not load your data at design time.
        If Not (System.ComponentModel.DesignerProperties.GetIsInDesignMode(Me)) Then
            'Load your data here and assign the result to the CollectionViewSource.
            Dim myCollectionViewSource As System.Windows.Data.CollectionViewSource = CType(Me.Resources("CustomersViewSource"), System.Windows.Data.CollectionViewSource)
            myCollectionViewSource.Source = GetCustomers()
        End If
    End Sub
    
    private void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
    
        // Do not load your data at design time.
        if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
        {
            //Load your data here and assign the result to the CollectionViewSource.
            System.Windows.Data.CollectionViewSource myCollectionViewSource = (System.Windows.Data.CollectionViewSource)this.Resources["customersViewSource"];
            myCollectionViewSource.Source = GetCustomers();
        }
    }
    

응용 프로그램 테스트

응용 프로그램을 빌드하고 실행하여 고객 레코드를 볼 수 있는지 확인합니다.

응용 프로그램을 테스트하려면

  1. 빌드 메뉴에서 솔루션 빌드를 클릭합니다. 솔루션이 오류 없이 빌드되는지 확인합니다.

  2. 응용 프로그램을 실행합니다.

  3. 데이터 표에 Customer가 3개 나타나는지 확인하고 선택한 고객의 주문이 주문 표에 표시되는지 확인합니다.

  4. 다른 고객을 선택하고 해당 고객의 주문만 표시되도록 주문 내용이 업데이트되는지 확인합니다.

  5. 응용 프로그램을 닫습니다.

다음 단계

이 연습을 완료하면 다음과 같은 관련 작업을 수행할 수 있습니다.

  • 변경 내용을 데이터 저장소에 다시 저장하는 방법을 학습합니다. 자세한 내용은 데이터 바인딩을 참조하십시오.

참고 항목

기타 리소스

Visual Studio에서 데이터 액세스

Data Access and Data Structures