Categories
C#

C# DataBinding


using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.CompilerServices;
 
namespace WindowsFormsApplication1
{
    public partial class Form2 : Form
    {
        public Form2()
        {
            InitializeComponent();
        }
 
        Test test;
        private void Form2_Load(object sender, EventArgs e)
        {
            test=new Test();
            label1.DataBindings.Add("Text", test, "Str");
            label2.DataBindings.Add("Text", test, "Str");
            label3.DataBindings.Add("Text", test, "Str");
            
        }
 
        private void textBox1_TextChanged(object sender, EventArgs e)
        {
            test.Str = textBox1.Text;
        }
 
    }
 
    //要使用绑定数据功能,需要模型支持INotifyPropertyChanged接口
    public class Test : INotifyPropertyChanged
    {
        string _str;
        public string Str
        {
            get
            {
                return _str;
            }
            set
            {
                _str = value;
                FireStrChanged();
            }
        }
 
        //必须实现INotifyPropertyChanged接口的此事件
        public event PropertyChangedEventHandler PropertyChanged;
 
        //要在.net4.0使用CallerMemberName特性,需要加上后面一段代码
        public void FireStrChanged([CallerMemberName] string propertyName="")
        {
            PropertyChanged.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }
 
    }
}
 
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
    public class CallerMemberNameAttribute : Attribute
    {
 
    }
 
    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
    public class CallerFilePathAttribute : Attribute
    {
 
    }
 
    [AttributeUsage(AttributeTargets.Parameter, Inherited = false)]
    public class CallerLineNumberAttribute : Attribute
    {
 
    }
}
————————————————
版权声明:本文为CSDN博主「naruto2017」的原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/szy759590387/article/details/89516163

Leave a Reply