WinForm 双向数据绑定

程序目标: 控件的属性值与对象的属性值双向绑定使窗口控件的属性值与对象的属性值保持一致。对窗口控件属性值更改后立即更新对象的属性值,对对象的属性值更改后立即更新窗口控件的属性值。

程序完整代码包:https://pan.baidu.com/s/1JPX0BJDNiEoczYE9xXL1ow

主要代码:

定义控件属性要绑定对象的类:Person

using System.ComponentModel;

namespace TempTest
{
    /// <summary>
    /// 要实现双向绑定需要继承System.ComponentModel.INotifyPropertyChange接口。若不继承此接口则只能单向绑定,对对象属性值的更改不会通知控件更新。
    /// </summary>
    class Person : INotifyPropertyChanged
    {
        #region 属性
        public string Name { get => mName; set { mName = value; SendChangeInfo("Name"); } }
        public string Address { get => mAddress; set { mAddress = value;SendChangeInfo("Address"); } }
        public int Age { get => mAge; set { mAge = value; SendChangeInfo("Age"); } }
        #endregion
        


        private string mName;
        private string mAddress;
        private int mAge;

        /// <summary>
        /// 属性改变后需要调用的方法,触发PropertyChanged事件。
        /// </summary>
        /// <param name="propertyName">属性名</param>
        private void SendChangeInfo(string propertyName)
        {
            if (this.PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }

        /// <summary>
        /// 实现的接口。
        /// </summary>
        public event PropertyChangedEventHandler PropertyChanged;
    }
}

Form:

using System;
using System.Diagnostics;
using System.Windows.Forms;
namespace TempTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private Person User;
        private void Form1_Load(object sender, EventArgs e)
        {
            //创建对象初始化属性
            User = new Person()
            {
                Name = "ABC",
                Address = "中国 湖南",
                Age = 30
            };

            //绑定数据
            textBoxName.DataBindings.Add("Text", User, "Name");
            textBoxAddress.DataBindings.Add("Text", User, "Address");
            textBoxAge.DataBindings.Add("Text", User, "Age");
        }

        /// <summary>
        /// 通过另外3个textBox改变对象属性值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonChangeValue_Click(object sender, EventArgs e)
        {
            User.Name = textBoxName2.Text;
            User.Address = textBoxAddress2.Text;
            int age;
            int.TryParse(textBoxAge2.Text, out age);
            User.Age = age;
            // textBoxName,textBoxAddress,textBoxAge的Text会自动更新
        }

        /// <summary>
        /// Debug输出对象属性值
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonShow_Click(object sender, EventArgs e)
        {
            Debug.WriteLine($"{User.Name},{User.Address},{User.Age}");
        }
    }
}
View Code

 

posted on 2019-01-15 02:37 IT菜鸟的博客 阅读(...) 评论(...) 编辑 收藏

导航

统计

公告