C# winform控件和对象双向数据绑定

实现目的:

控件和对象双向数据绑定

实现结果:

1. 对象值 -> 控件值
2. 控件值 -> 对象值

C# winform控件和对象双向数据绑定_第1张图片

C# winform控件和对象双向数据绑定_第2张图片

复制代码

using System;
using System.Windows.Forms;

namespace ControlDataBind
{
    public partial class MainForm : Form
    {
        People people = new People();

        public MainForm()
        {
            InitializeComponent();
        }

        private void btnBind_Click(object sender, EventArgs e)
        {
            people.Name = "对象";
            people.Age = 3;
            txtName.DataBindings.Add("Text", people, "Name");
            txtAge.DataBindings.Add("Text", people, "Age");
        }

        private void btnGetData_Click(object sender, EventArgs e)
        {
            MessageBox.Show($"对象信息,Name={people.Name},Age={people.Age}");
        }

        private void btnSetData_Click(object sender, EventArgs e)
        {
            people.Name = "111";
        }
    }
}

复制代码

复制代码

using System.ComponentModel;

namespace ControlDataBind
{
    public class People : INotifyPropertyChanged
    {
        string _name;
        int _age;

        public string Name
        {
            get { return _name; }
            set
            {
                _name = value;
                OnPropertyChanged(nameof(Name));
            }
        }

        public int Age
        {
            get { return _age; }
            set
            {
                _age = value;
                OnPropertyChanged(nameof(Age));
            }
        }

        public event PropertyChangedEventHandler PropertyChanged;

        protected virtual void OnPropertyChanged(string propertyName)  //属性变更通知
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

复制代码

你可能感兴趣的:(c#,开发语言)