C#模拟单向数据绑定
在说明事件之前,首先要说明下委托,简单来说就是一种特殊的变量,该变量可以赋值一个函数,但并不是所有的函数都可以赋值,需要符合委托类型的函数才可以赋值,就像字
符串类型的数据不能赋值给整型的变量一样。
WPF中数据绑定的通知就是事件实现的。
贴代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Reflection; 5 using System.Text; 6 using System.Threading; 7 using System.Threading.Tasks; 8 using System.Timers; 9 10 namespace EventHandleSample 11 { 12 class Program 13 { 14 static void Main(string[] args) 15 { 16 Book book = new Book(); 17 UIPanel panel = new UIPanel(); 18 panel.Binding(book); 19 for (int i = 0; i < 10;i++ ) 20 { 21 book.ID = i.ToString(); 22 book.BookName = "Book" + i; 23 book.Describe = "Describe" + i; 24 Console.WriteLine(""); 25 Thread.Sleep(200); 26 } 27 Console.ReadKey(); 28 } 29 30 } 31 //声明委托类型 32 public delegate void AttributeChanged(object sender,string propertyName); 33 34 //界面显示数据 35 public class UIPanel 36 { 37 public void DataChanged(object sender, string propertyName) 38 { 39 Console.Write("Book entity has been changed!Update " + propertyName + "UI value from "+ this.GetType().GetProperty(propertyName + "UI").GetValue(this)+" to "); 40 PropertyInfo info = this.GetType().GetProperty(propertyName+"UI"); 41 info.SetValue(this,sender.GetType().GetProperty(propertyName).GetValue(sender)); 42 Console.WriteLine(this.GetType().GetProperty(propertyName + "UI").GetValue(this)); 43 } 44 45 public void Binding(object source) 46 { 47 if(source is Book){ 48 Book book = source as Book; 49 book.OnChanged += this.DataChanged; 50 } 51 } 52 53 54 //界面显示ID 55 public string IDUI { set; get; } 56 //界面显示书名 57 public string BookNameUI { set; get; } 58 //界面显示简介 59 public string DescribeUI { set; get; } 60 } 61 //实体类 62 public class Book 63 { 64 public event AttributeChanged OnChanged; 65 //编号 66 private string _id; 67 public string ID 68 { 69 set 70 { 71 //通知对应的属性改变 72 this.NotifyChanged("ID"); 73 this._id = value; 74 } 75 get 76 { 77 return _id; 78 } 79 } 80 //书名 81 private string _bookName; 82 public string BookName { 83 set 84 { 85 //通知对应的属性改变 86 this.NotifyChanged("BookName"); 87 this._bookName = value; 88 } 89 get 90 { 91 return _bookName; 92 } 93 } 94 //简介 95 private string _describe; 96 public string Describe { 97 set 98 { 99 //通知对应的属性改变 100 this.NotifyChanged("Describe"); 101 this._describe = value; 102 } 103 get 104 { 105 return _describe; 106 } 107 } 108 109 private void NotifyChanged(string propertyName) 110 { 111 //当这个事件不为空时 112 if (OnChanged != null) 113 { 114 //调用该事件的处理函数,即 115 OnChanged(this,propertyName); 116 } 117 } 118 } 119 }
只是个人的理解,有不对的地方希望各大牛能够指点一二。