다음을 통해 공유


변경 알림(Windows Forms .NET)을 사용한 훌륭한 데이터 원본 디자인

Windows Forms 데이터 바인딩의 가장 중요한 개념 중 하나는 변경 알림입니다. 데이터 원본 및 바인딩된 컨트롤에 항상 최신 데이터가 있는지 확인하려면 데이터 바인딩에 대한 변경 알림을 추가해야 합니다. 특히 바인딩된 컨트롤이 데이터 원본에 적용된 변경 내용에 대해 알림을 받도록 합니다. 데이터 원본에는 컨트롤의 바인딩된 속성에 대한 변경 내용이 표시됩니다.

데이터 바인딩의 종류에 따라, 다양한 종류의 변경 알림이 있습니다.

  • 단순 바인딩. 단일 컨트롤 속성이 개체의 단일 인스턴스에 바인딩됩니다.

  • 목록 기반 바인딩. 목록의 항목 속성에 바인딩된 단일 컨트롤 속성 또는 개체 목록에 바인딩된 컨트롤 속성을 포함할 수 있습니다.

또는 데이터 바인딩에 사용하려는 Windows Forms 컨트롤을 생성하는 경우, PropertyNameChanged 패턴을 컨트롤에 적용합니다. 컨트롤에 패턴을 적용하면 컨트롤의 바인딩된 속성이 변경되어 데이터 원본으로 전파됩니다.

단순 바인딩에 대한 변경 알림

단순 바인딩의 경우, 비즈니스 개체는 바인딩된 속성의 값이 변경될 때 변경 알림을 제공해야 합니다. 비즈니스 개체의 각 속성에 대해 PropertyNameChanged 이벤트를 노출하여 변경 알림을 제공할 수 있습니다. 또한, BindingSource 또는 비즈니스 개체가 INotifyPropertyChanged 인터페이스를 구현하고 속성 값이 변경될 때 PropertyChanged 이벤트를 제기하는 원하는 방법으로 비즈니스 개체를 컨트롤에 바인딩해야 합니다. INotifyPropertyChanged 인터페이스를 구현하는 개체를 사용할 때는 개체를 컨트롤에 바인딩하기 위해 BindingSource을(를) 사용해야 하는 것은 아닙니다. 그러나 BindingSource을(를) 사용하는 것이 좋습니다.

목록 기반 바인딩에 대한 변경 알림

Windows Forms는 바인딩된 목록에 따라 속성 변경목록 변경 정보를 바인딩된 컨트롤에 제공합니다. 속성 변경은 목록 항목 속성 값 변경이며 목록 변경은 삭제되거나 목록에 추가된 항목입니다. 따라서, 데이터 바인딩에 사용된 목록은 IBindingList를 구현해야 합니다. 이것은 두 가지 유형의 변경 알림을 모두 제공합니다. BindingList<T>IBindingList의 일반 구현이며 Windows Forms 데이터 바인딩과 함께 사용하도록 설계되었습니다. INotifyPropertyChanged를 구현하는 비즈니스 개체 유형을 포함하는 BindingList를 생성할 수 있으며 목록은 PropertyChanged 이벤트를 자동으로 ListChanged 이벤트로 변환합니다. 바인딩된 목록이 IBindingList이(가) 아닌 경우, BindingSource 구성 요소를 사용하여 개체의 목록을 Windows Forms 컨트롤로 바인딩해야 합니다. BindingSource 구성 요소는 BindingList의 변환과 유사한 속성-목록 변환을 제공합니다. 자세한 내용은 방법: BindingSource와 INotifyPropertyChanged 인터페이스를 사용하여 변경 내용 알림 발생을 참조하세요.

사용자 지정 컨트롤에 대한 변경 알림

마지막으로, 컨트롤 측에서 데이터에 바인딩되도록 설계된 각 속성에 대해 PropertyNameChanged 이벤트를 노출시켜야 합니다. 그러면 컨트롤 속성의 변경 사항이 바인딩된 데이터 원본으로 전파됩니다. 자세한 내용은 PropertyNameChanged 패턴 적용을 참조하세요.

PropertyNameChanged 패턴 적용

다음 코드 예제에서는 PropertyNameChanged 패턴을 사용자 지정 컨트롤에 적용하는 방법을 보여 줍니다. Windows Forms 데이터 바인딩 엔진에서 사용되는 사용자 지정 컨트롤을 구현할 때 이 패턴을 적용합니다.

// This class implements a simple user control
// that demonstrates how to apply the propertyNameChanged pattern.
[ComplexBindingProperties("DataSource", "DataMember")]
public class CustomerControl : UserControl
{
    private DataGridView dataGridView1;
    private Label label1;
    private DateTime lastUpdate = DateTime.Now;

    public EventHandler DataSourceChanged;

    public object DataSource
    {
        get
        {
            return this.dataGridView1.DataSource;
        }
        set
        {
            if (DataSource != value)
            {
                this.dataGridView1.DataSource = value;
                OnDataSourceChanged();
            }
        }
    }

    public string DataMember
    {
        get { return this.dataGridView1.DataMember; }

        set { this.dataGridView1.DataMember = value; }
    }

    private void OnDataSourceChanged()
    {
        if (DataSourceChanged != null)
        {
            DataSourceChanged(this, new EventArgs());
        }
    }

    public CustomerControl()
    {
        this.dataGridView1 = new System.Windows.Forms.DataGridView();
        this.label1 = new System.Windows.Forms.Label();
        this.dataGridView1.ColumnHeadersHeightSizeMode =
           System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
        this.dataGridView1.ImeMode = System.Windows.Forms.ImeMode.Disable;
        this.dataGridView1.Location = new System.Drawing.Point(100, 100);
        this.dataGridView1.Size = new System.Drawing.Size(500,500);
                    
        this.dataGridView1.TabIndex = 1;
        this.label1.AutoSize = true;
        this.label1.Location = new System.Drawing.Point(50, 50);
        this.label1.Name = "label1";
        this.label1.Size = new System.Drawing.Size(76, 13);
        this.label1.TabIndex = 2;
        this.label1.Text = "Customer List:";
        this.Controls.Add(this.label1);
        this.Controls.Add(this.dataGridView1);
        this.Size = new System.Drawing.Size(450, 250);
    }
}
' This class implements a simple user control 
' that demonstrates how to apply the propertyNameChanged pattern.
<ComplexBindingProperties("DataSource", "DataMember")>
Public Class CustomerControl
    Inherits UserControl
    Private dataGridView1 As DataGridView
    Private label1 As Label
    Private lastUpdate As DateTime = DateTime.Now

    Public DataSourceChanged As EventHandler

    Public Property DataSource() As Object
        Get
            Return Me.dataGridView1.DataSource
        End Get
        Set
            If DataSource IsNot Value Then
                Me.dataGridView1.DataSource = Value
                OnDataSourceChanged()
            End If
        End Set
    End Property

    Public Property DataMember() As String
        Get
            Return Me.dataGridView1.DataMember
        End Get
        Set
            Me.dataGridView1.DataMember = Value
        End Set
    End Property

    Private Sub OnDataSourceChanged()
        If (DataSourceChanged IsNot Nothing) Then
            DataSourceChanged(Me, New EventArgs())
        End If

    End Sub

    Public Sub New()
        Me.dataGridView1 = New System.Windows.Forms.DataGridView()
        Me.label1 = New System.Windows.Forms.Label()
        Me.dataGridView1.ColumnHeadersHeightSizeMode =
           System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize
        Me.dataGridView1.ImeMode = System.Windows.Forms.ImeMode.Disable
        Me.dataGridView1.Location = New System.Drawing.Point(19, 55)
        Me.dataGridView1.Size = New System.Drawing.Size(550, 150)
        Me.dataGridView1.TabIndex = 1
        Me.label1.AutoSize = True
        Me.label1.Location = New System.Drawing.Point(19, 23)
        Me.label1.Name = "label1"
        Me.label1.Size = New System.Drawing.Size(76, 13)
        Me.label1.TabIndex = 2
        Me.label1.Text = "Customer List:"
        Me.Controls.Add(Me.label1)
        Me.Controls.Add(Me.dataGridView1)
        Me.Size = New System.Drawing.Size(650, 300)
    End Sub
End Class

INotifyPropertyChanged 인터페이스 구현

다음 코드 예제를 구현 하는 방법에 설명 합니다 INotifyPropertyChanged 인터페이스입니다. Windows Forms 데이터 바인딩에 사용되는 비즈니스 개체에서 이 인터페이스를 구현합니다. 구현된 경우 이 인터페이스는 비즈니스 개체의 속성 변경 내용을 바인딩된 컨트롤에 전달합니다.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Runtime.CompilerServices;
using System.Windows.Forms;

// Change the namespace to the project name.
namespace binding_control_example
{
    // This form demonstrates using a BindingSource to bind
    // a list to a DataGridView control. The list does not
    // raise change notifications. However the DemoCustomer1 type
    // in the list does.
    public partial class Form3 : Form
    {
        // This button causes the value of a list element to be changed.
        private Button changeItemBtn = new Button();

        // This DataGridView control displays the contents of the list.
        private DataGridView customersDataGridView = new DataGridView();

        // This BindingSource binds the list to the DataGridView control.
        private BindingSource customersBindingSource = new BindingSource();

        public Form3()
        {
            InitializeComponent();

            // Set up the "Change Item" button.
            this.changeItemBtn.Text = "Change Item";
            this.changeItemBtn.Dock = DockStyle.Bottom;
            this.changeItemBtn.Height = 100;
            //this.changeItemBtn.Click +=
              //  new EventHandler(changeItemBtn_Click);
            this.Controls.Add(this.changeItemBtn);

            // Set up the DataGridView.
            customersDataGridView.Dock = DockStyle.Top;
            this.Controls.Add(customersDataGridView);

            this.Size = new Size(400, 200);
        }

        private void Form3_Load(object sender, EventArgs e)
        {
            this.Top = 100;
            this.Left = 100;
            this.Height = 600;
            this.Width = 1000;

            // Create and populate the list of DemoCustomer objects
            // which will supply data to the DataGridView.
            BindingList<DemoCustomer1> customerList = new ();
            customerList.Add(DemoCustomer1.CreateNewCustomer());
            customerList.Add(DemoCustomer1.CreateNewCustomer());
            customerList.Add(DemoCustomer1.CreateNewCustomer());

            // Bind the list to the BindingSource.
            this.customersBindingSource.DataSource = customerList;

            // Attach the BindingSource to the DataGridView.
            this.customersDataGridView.DataSource =
                this.customersBindingSource;
        }

        // Change the value of the CompanyName property for the first
        // item in the list when the "Change Item" button is clicked.
        void changeItemBtn_Click(object sender, EventArgs e)
        {
            // Get a reference to the list from the BindingSource.
            BindingList<DemoCustomer1>? customerList =
                this.customersBindingSource.DataSource as BindingList<DemoCustomer1>;

            // Change the value of the CompanyName property for the
            // first item in the list.
            customerList[0].CustomerName = "Tailspin Toys";
            customerList[0].PhoneNumber = "(708)555-0150";
        }
                
    }

    // This is a simple customer class that
    // implements the IPropertyChange interface.
    public class DemoCustomer1 : INotifyPropertyChanged
    {
        // These fields hold the values for the public properties.
        private Guid idValue = Guid.NewGuid();
        private string customerNameValue = String.Empty;
        private string phoneNumberValue = String.Empty;

        public event PropertyChangedEventHandler PropertyChanged;

        // This method is called by the Set accessor of each property.
        // The CallerMemberName attribute that is applied to the optional propertyName
        // parameter causes the property name of the caller to be substituted as an argument.
        private void NotifyPropertyChanged([CallerMemberName] String propertyName = "")
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        // The constructor is private to enforce the factory pattern.
        private DemoCustomer1()
        {
            customerNameValue = "Customer";
            phoneNumberValue = "(312)555-0100";
        }

        // This is the public factory method.
        public static DemoCustomer1 CreateNewCustomer()
        {
            return new DemoCustomer1();
        }

        // This property represents an ID, suitable
        // for use as a primary key in a database.
        public Guid ID
        {
            get
            {
                return this.idValue;
            }
        }

        public string CustomerName
        {
            get
            {
                return this.customerNameValue;
            }

            set
            {
                if (value != this.customerNameValue)
                {
                    this.customerNameValue = value;
                    NotifyPropertyChanged();
                }
            }
        }

        public string PhoneNumber
        {
            get
            {
                return this.phoneNumberValue;
            }

            set
            {
                if (value != this.phoneNumberValue)
                {
                    this.phoneNumberValue = value;
                    NotifyPropertyChanged();
                }
            }
        }
    }
}
Imports System.Collections.Generic
Imports System.ComponentModel
Imports System.Drawing
Imports System.Runtime.CompilerServices
Imports System.Windows.Forms

' This form demonstrates using a BindingSource to bind
' a list to a DataGridView control. The list does not
' raise change notifications. However the DemoCustomer1 type 
' in the list does.
Public Class Form3
    Inherits System.Windows.Forms.Form
    ' This button causes the value of a list element to be changed.
    Private changeItemBtn As New Button()

    ' This DataGridView control displays the contents of the list.
    Private customersDataGridView As New DataGridView()

    ' This BindingSource binds the list to the DataGridView control.
    Private customersBindingSource As New BindingSource()

    Public Sub New()
        InitializeComponent()
        ' Set up the "Change Item" button.
        Me.changeItemBtn.Text = "Change Item"
        Me.changeItemBtn.Dock = DockStyle.Bottom
        Me.changeItemBtn.Size = New System.Drawing.Size(100, 100)
        AddHandler Me.changeItemBtn.Click, AddressOf changeItemBtn_Click
        Me.Controls.Add(Me.changeItemBtn)

        ' Set up the DataGridView.
        customersDataGridView.Dock = DockStyle.Top
        Me.Controls.Add(customersDataGridView)
        Me.Size = New Size(400, 200)
    End Sub

    Private Sub Form3_Load(ByVal sender As System.Object,
        ByVal e As System.EventArgs) Handles Me.Load
        Me.Top = 100
        Me.Left = 100
        Me.Height = 600
        Me.Width = 1000
        ' Create and populate the list of DemoCustomer1 objects
        ' which will supply data to the DataGridView.
        Dim customerList As New BindingList(Of DemoCustomer1)
        customerList.Add(DemoCustomer1.CreateNewCustomer())
        customerList.Add(DemoCustomer1.CreateNewCustomer())
        customerList.Add(DemoCustomer1.CreateNewCustomer())

        ' Bind the list to the BindingSource.
        Me.customersBindingSource.DataSource = customerList

        ' Attach the BindingSource to the DataGridView.
        Me.customersDataGridView.DataSource = Me.customersBindingSource
    End Sub

    ' This event handler changes the value of the CompanyName
    ' property for the first item in the list.
    Private Sub changeItemBtn_Click(ByVal sender As Object, ByVal e As EventArgs)
        ' Get a reference to the list from the BindingSource.
        Dim customerList As BindingList(Of DemoCustomer1) =
            CType(customersBindingSource.DataSource, BindingList(Of DemoCustomer1))

        ' Change the value of the CompanyName property for the 
        ' first item in the list.
        customerList(0).CustomerName = "Tailspin Toys"
        customerList(0).PhoneNumber = "(708)555-0150"
    End Sub
End Class

' This class implements a simple customer type 
' that implements the IPropertyChange interface.
Public Class DemoCustomer1
    Implements INotifyPropertyChanged

    ' These fields hold the values for the public properties.
    Private idValue As Guid = Guid.NewGuid()
    Private customerNameValue As String = String.Empty
    Private phoneNumberValue As String = String.Empty

    Public Event PropertyChanged As PropertyChangedEventHandler _
        Implements INotifyPropertyChanged.PropertyChanged

    ' This method is called by the Set accessor of each property.
    ' The CallerMemberName attribute that is applied to the optional propertyName
    ' parameter causes the property name of the caller to be substituted as an argument.
    Private Sub NotifyPropertyChanged(<CallerMemberName()> Optional ByVal propertyName As String = Nothing)
        RaiseEvent PropertyChanged(Me, New PropertyChangedEventArgs(propertyName))
    End Sub

    ' The constructor is private to enforce the factory pattern.
    Private Sub New()
        customerNameValue = "Customer"
        phoneNumberValue = "(312)555-0100"
    End Sub

    ' This is the public factory method.
    Public Shared Function CreateNewCustomer() As DemoCustomer1
        Return New DemoCustomer1()
    End Function

    ' This property represents an ID, suitable
    ' for use as a primary key in a database.
    Public ReadOnly Property ID() As Guid
        Get
            Return Me.idValue
        End Get
    End Property

    Public Property CustomerName() As String
        Get
            Return Me.customerNameValue
        End Get

        Set(ByVal value As String)
            If Not (value = customerNameValue) Then
                Me.customerNameValue = value
                NotifyPropertyChanged()
            End If
        End Set
    End Property

    Public Property PhoneNumber() As String
        Get
            Return Me.phoneNumberValue
        End Get

        Set(ByVal value As String)
            If Not (value = phoneNumberValue) Then
                Me.phoneNumberValue = value
                NotifyPropertyChanged()
            End If
        End Set
    End Property
End Class

바인딩 동기화

Windows Forms에서 데이터 바인딩을 구현하는 동안 여러 컨트롤이 동일한 데이터 원본에 바인딩되는 경우가 많습니다. 경우에 따라 컨트롤의 바인딩된 속성이 서로 및 데이터 원본과 동기화된 상태로 유지되도록 추가 단계를 수행해야 할 수 있습니다. 이러한 단계는 다음 두 가지 경우에 필요합니다.

전자의 경우 BindingSource를 사용하여 데이터 원본을 컨트롤에 바인딩할 수 있습니다. 후자의 경우 BindingSource를 사용하고 BindingComplete 이벤트를 처리하고 연결된 BindingManagerBase에서 EndCurrentEdit를 호출합니다.

이 개념을 구현하는 방법에 대한 자세한 내용은 BindingComplete API 참조 페이지를 참조하세요.

참고 항목