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

实现目的:

控件和对象双向数据绑定

 

实现结果:

1. 对象值 -> 控件值
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));
            }
        }
    }
}

 

posted @ 2023-09-04 17:25  CHHC  阅读(692)  评论(0编辑  收藏  举报