在C# WinForms中,实现数据绑定的方法如下:
INotifyPropertyChanged接口。这个接口允许你的数据类在属性值发生变化时通知绑定的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,并设置其DataBindings属性。例如,将Label的Text属性绑定到Person对象的Name属性:public partial class MainForm : Form
{
public MainForm()
{
InitializeComponent();
Person person = new Person { Name = "John Doe", Age = 30 };
labelName.DataBindings.Add("Text", person, "Name");
}
}
在这个例子中,我们创建了一个Person对象,并将其Name属性绑定到labelName的Text属性。当Person对象的Name属性发生变化时,labelName的文本也会自动更新。
BindingList<T>或ObservableCollection<T>。例如,将一个BindingList<Person>绑定到一个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";
}
}
在这个例子中,我们将一个BindingList<Person>绑定到comboBoxPeople的DataSource属性,并设置DisplayMember属性为Name。这样,ComboBox将显示Person对象的名称。当BindingList中的数据发生变化时,ComboBox将自动更新。