实现目的:
控件和对象双向数据绑定
实现结果:
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"; } } }
文章来源:https://www.toymoban.com/news/detail-695453.html
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)); } } } }
文章来源地址https://www.toymoban.com/news/detail-695453.html
到了这里,关于C# winform控件和对象双向数据绑定的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!