C#知識點集錦(五)資料繫結,觀察者模式
阿新 • • 發佈:2020-12-10
public partial class Form1 : Form { MyData _myData = null; public Form1() { InitializeComponent(); } private void Form1_Load(object sender, EventArgs e) { _myData = new MyData(); textBox1.DataBindings.Add("Text", _myData, "TheValue", false, DataSourceUpdateMode.OnPropertyChanged); textBox2.DataBindings.Add("Text", _myData, "TheValue", false, DataSourceUpdateMode.Never); } private void textBox3_TextChanged(object sender, EventArgs e) { _myData.TheValue= textBox3.Text; } } public class MyData:INotifyPropertyChanged { private string _theValue = string.Empty; public string TheValue { get { return _theValue; } set { if (string.IsNullOrEmpty(value) || value == _theValue)return; _theValue = value; NotifyPropertyChanged(() => TheValue); } } public event PropertyChangedEventHandler PropertyChanged; public void NotifyPropertyChanged<T>(Expression<Func<T>> property) { if (PropertyChanged == null) return; var memberExpression = property.Body as MemberExpression; if (memberExpression == null) return; PropertyChanged.Invoke(this, new PropertyChangedEventArgs(memberExpression.Member.Name)); } }
觀察者模式
https://www.cnblogs.com/xmfdsh/p/4047114.html