当前位置:首页 > Windows程序 > 正文

WPF学习(二) - 绑定

2021-05-25 Windows程序

绑定,这个看起来很神奇的东西,于我这种喜欢刨根儿的人而言,理解起来非常困难。
    WPF绑定的核心思想是:数据层属性值的改变,能反应给展示层,反之亦然,并且这个响应的过程能被分离出来。


    传统Winform编程更加原始,没有那么多隐藏的(implicate)技术。我就以winform的实现方式来领会WPF的机制。

public class DataLayer { public delegate void TextChangedEventHandler ( object sender, EventArgs e ); public event TextChangedEventHandler TextChanged; private string text = ""; public string Text { get { return text; } set { if ( text != value ) { text = value; if ( this.TextChanged != null ) this.TextChanged ( this, new EventArgs ( ) ); } } } }

数据层代码

public partial class PresentationLayer : Form { TextBox ui = new TextBox ( ); DataLayer data = new DataLayer ( ); public PresentationLayer ( ) { InitializeComponent ( ); this.Controls.Add ( ui ); ui.TextChanged += new System.EventHandler ( this.PresentationLayerTextChanged ); data.TextChanged += new DataLayer.TextChangedEventHandler ( this.DataLayerTextChanged ); } private void PresentationLayerTextChanged ( object sender, EventArgs e ) { data.Text = ui.Text; } private void DataLayerTextChanged ( object sender, EventArgs e ) { ui.Text = data.Text; } }

展示层代码

这样就实现了前、后台数据的同步。缺点有三方面:

  1、每个属性的数据同步,功能单一,内容相同。没有必要在数据层对每个属性的响应事件都单独定义事件委托。
  2、为了保持数据同步,需要在展示层编写大量的数据同步代码。如果有很多个属性,重复的工作量非常大。
  3、data作为PresentationLayer的成员,增加了耦合度。数据层和展示层没有完全分隔开。

  问题1很好解决,从数据层抽象出一个接口事件,并在事件参数中要求说明激发事件的属性名

public interface INotifyPropertyChanged { event PropertyChangedEventHandler PropertyChanged; } public delegate void PropertyChangedEventHandler ( object sender, PropertyChangedEventArgs e ); public class PropertyChangedEventArgs : EventArgs { private readonly string propertyName; public PropertyChangedEventArgs ( string propertyName ) { this.propertyName = propertyName; } public virtual string PropertyName { get { return this.propertyName; } } }

抽象出来的接口事件

这样,原始的DataLayer就变成这样

public class DataLayerExt : INotifyPropertyChanged { public event PropertyChangedEventHandler PropertyChanged; private string text = ""; public string Text { get { return text; } set { if ( text != value ) { text = value; if ( this.PropertyChanged != null ) this.PropertyChanged ( this, new PropertyChangedEventArgs ( "Text" ) ); } } } }

DataLayerExt

  问题2从逻辑上也不难解决,定义一个静态的方法,方法的参数要说明是哪两个对象的哪两个属性需要同步,并记录这种同步关系

温馨提示: 本文由Jm博客推荐,转载请保留链接: https://www.jmwww.net/file/70658.html