使用變更通知設計絕佳的資料來源 (Windows Forms .NET)
Windows Forms 資料繫結最重要的概念之一是變更通知。 若要確保您的資料來源和繫結控制項一律具有最新的資料,您必須新增資料繫結的變更通知。 具體來說,您想要確保繫結控制項會收到對其資料來源進行變更的通知。 資料來源會收到控制項繫結屬性變更的通知。
根據資料繫結的類型而定,有不同類型的變更通知:
簡單繫結,其中單一控制項屬性會繫結至物件的單一執行個體。
清單型繫結,可包含繫結至清單中項目屬性的單一控制項屬性,或繫結至物件清單的控制項屬性。
此外,如果您正在建立要用於資料繫結的 Windows Forms 控制項,則必須將 PropertyName 變更模式套用至控制項。 將模式套用至控制項會導致控制項繫結屬性的變更傳播至資料來源。
簡單繫結的變更通知
對於簡單繫結,當繫結屬性的值變更時,商務物件必須提供變更通知。 您可以公開商務物件中每個屬性的 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 介面引發變更告知。
自訂控制項的變更通知
最後,從控制項端,您必須針對設計用來繫結至資料的每個屬性公開 PropertyName 變更事件。 然後,控制項屬性的變更會傳播至繫結的資料來源。 如需詳細資訊,請參閱套用 PropertyNameChanged 模式。
套用 PropertyNameChanged 模式
下列程式碼範例示範如何將 PropertyName 變更模式套用至自訂控制項。 當您實作與 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 中實作資料繫結期間,多個控制項會繫結至相同的資料來源。 在某些情況下,可能需要採取額外的步驟,以確保控制項的繫結屬性彼此和與資料來源保持同步。 在兩種情況下,這些步驟是必要的:
如果資料來源未實作 IBindingList,因此會產生 ItemChanged 類型的 ListChanged 事件。
如果資料來源實作 IEditableObject。
在先前的案例中,您可以使用 BindingSource 將資料來源 繫結至控制項。 在後者的情況下,您會使用 BindingSource
並處理 BindingComplete 事件,並在相關聯的 BindingManagerBase 上呼叫 EndCurrentEdit。
如需實作此概念的詳細資訊,請參閱 BindingComplete API 參考頁面。