在C# WinForms中,實(shí)現(xiàn)數(shù)據(jù)綁定的方法如下:
INotifyPropertyChanged
接口。這個(gè)接口允許你的數(shù)據(jù)類在屬性值發(fā)生變化時(shí)通知綁定的UI控件。例如:public class Person : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
private string _name;
public string Name
{
get { return _name; }
set
{
_name = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Name)));
}
}
private int _age;
public int Age
{
get { return _age; }
set
{
_age = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(Age)));
}
}
}
Label
或TextBox
,并設(shè)置其DataBindings
屬性。例如,將Label
的Text
屬性綁定到Person
對(duì)象的Name
屬性:public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
Person person = new Person { Name = "John Doe", Age = 30 };
labelName.DataBindings.Add("Text", person, "Name");
}
}
在這個(gè)例子中,我們創(chuàng)建了一個(gè)Person
對(duì)象,并將其Name
屬性綁定到labelName
的Text
屬性。當(dāng)Person
對(duì)象的Name
屬性發(fā)生變化時(shí),labelName
的文本也會(huì)自動(dòng)更新。
BindingList<T>
或ObservableCollection<T>
。例如,將一個(gè)BindingList<Person>
綁定到一個(gè)ComboBox
:public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
BindingList<Person> people = new BindingList<Person>
{
new Person { Name = "John Doe", Age = 30 },
new Person { Name = "Jane Smith", Age = 28 }
};
comboBoxPeople.DataSource = people;
comboBoxPeople.DisplayMember = "Name";
}
}
在這個(gè)例子中,我們將一個(gè)BindingList<Person>
綁定到comboBoxPeople
的DataSource
屬性,并設(shè)置DisplayMember
屬性為Name
。這樣,ComboBox
將顯示Person
對(duì)象的名稱。當(dāng)BindingList
中的數(shù)據(jù)發(fā)生變化時(shí),ComboBox
將自動(dòng)更新。