c# winform 怎樣實(shí)現(xiàn)數(shù)據(jù)綁定

c#
小樊
81
2024-11-16 11:31:39

在C# WinForms中,實(shí)現(xiàn)數(shù)據(jù)綁定的方法如下:

  1. 首先,確保你的數(shù)據(jù)源是一個(gè)類,該類應(yīng)該實(shí)現(xiàn)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)));
        }
    }
}
  1. 在WinForms窗體上,創(chuàng)建一個(gè)數(shù)據(jù)綁定控件,例如LabelTextBox,并設(shè)置其DataBindings屬性。例如,將LabelText屬性綁定到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屬性綁定到labelNameText屬性。當(dāng)Person對(duì)象的Name屬性發(fā)生變化時(shí),labelName的文本也會(huì)自動(dòng)更新。

  1. 如果你需要將數(shù)據(jù)綁定到復(fù)雜的數(shù)據(jù)結(jié)構(gòu),例如列表或字典,你可以使用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>綁定到comboBoxPeopleDataSource屬性,并設(shè)置DisplayMember屬性為Name。這樣,ComboBox將顯示Person對(duì)象的名稱。當(dāng)BindingList中的數(shù)據(jù)發(fā)生變化時(shí),ComboBox將自動(dòng)更新。

0