WPF Learning (2)-binding and wpf learning binding

Source: Internet
Author: User

WPF Learning (2)-binding and wpf learning binding

Binding is a magical thing. It is very difficult for people like me to understand binding.
The core idea of WPF binding is that changes in the attribute values of the data layer can be reflected to the display layer, and vice versa, and the response process can be separated.


Traditional Winform programming is more primitive, directly referring to the essence. I will understand the WPF mechanism through the implementation of winform.

Data Layer DataLayer

    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 ( ) );                }            }        }    }

Presentation Layer PresentationLayer

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;        }    }

In this way, data is synchronized between the front and back ends. There are three disadvantages:

1. Data Synchronization for each attribute has a single function and the same content. There is no need to define event Delegation for each attribute RESPONSE event at the data layer.
2. To maintain data synchronization, you need to write a large amount of data synchronization code at the presentation layer. If there are many attributes, the repetitive workload is very large.
3. As a member of PresentationLayer, data increases coupling. The data layer and the presentation layer are not completely separated.

Problem 1 is well solved. An interface event is abstracted from the data layer and the attribute name of the event to be stimulated must be specified in the event parameters.

    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;            }        }    }

In this way, the original DataLayer becomes like this.

    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" ) );                }            }        }    }

Problem 2 is logically not difficult to solve. Define a static method. The parameters of the method should indicate which two properties of the two objects need to be synchronized, and record the synchronization relationship.

Public class BindingOperations {static List <BindingRelative> lstBindingRelative = new List <BindingRelative> (); // The Source and target types should be objects. Here, only the semantics is expressed, completely implement public static void SetBinding (TextBox uiObject, string uiPropertyName, DataLayerExt dataObject, string dataPropertyName) {// use the list to record the synchronization relationship lstBindingRelative. add (new BindingRelative () {UIObject = uiObject, UIObjectPropertyName = uiPropertyName, DataObject = dataObject, DataObjectPropertyName = dataPropertyName}); // bind the synchronization event uiObject. textChanged + = new EventHandler (uiObject_TextChanged); dataObject. propertyChanged + = new PropertyChangedEventHandler (target_PropertyChanged);} static void uiObject_TextChanged (object sender, EventArgs e) {foreach (BindingRelative item in lstBindingRelative) {if (item. UIObjectPropertyName = "Text") {// the general method should be like this // item. source. sourcePropertyName = item. target. dataPropertyName; item. dataObject. text = item. UIObject. text; break ;}} static void target_PropertyChanged (object sender, PropertyChangedEventArgs e) {foreach (BindingRelative item in lstBindingRelative) {if (item. dataObjectPropertyName = e. propertyName) {// modify the data on the ui Layer. The following sentence can only simulate semantics, which is very difficult to implement. // item. source. sourcePropertyName = item. target. dataPropertyName; item. UIObject. text = item. dataObject. text; break ;}}}// defines a public class BindingRelative {public TextBox UIObject; public string UIObjectPropertyName; public DataLayerExt DataObject; public string DataObjectPropertyName ;}

In this way, the presentation layer only needs to design the style of the interface, define the display elements in the interface, and completely separate from the background data. In this way, problem 1 is also resolved.

    public partial class PresentationLayerExt : Form    {        public TextBox ui = new TextBox ( );        public PresentationLayerExt ( )        {            InitializeComponent ( );            this.Controls.Add ( ui );        }    }

Of course, the logical relationship should be established, but not in the presentation layer, but outside, for example, in the Main () function.

Static class Program {// <summary> // main entry point of the application. /// </Summary> [STAThread] static void Main () {Application. EnableVisualStyles (); Application. SetCompatibleTextRenderingDefault (false );
PresentationLayerExt p = new PresentationLayerExt (); DataLayerExt d = new DataLayerExt (); BindingOperations. setBinding (p. ui, "Text", d, "Text"); Application. run (p );}}

Above, we use Winform to implement data synchronization and separate the data layer from the presentation layer. In Winform, it is very difficult to obtain the attributes of an object based on the attribute name string. The SetBinding method for defining associations has many drawbacks and is almost no universal. However, this does not prevent the running mechanism of the WPF binding technology from being understood through the Winform example.

The binding technology of WPF achieves the same principle of data synchronization between the data layer and the display layer:
The classes at the data layer must be derived from the INotifyPropertyChanged interface in System. ComponentModel,
Each class must contain the PropertyChanged event. When the property value changes, this event is triggered. The attribute name is input in the event parameter.

The data synchronization relationship is established by the SetBinding method of BindingOperations.

In WPF, the last two parameters of the SetBinding method are packaged as Binding objects.

In this way, the object parameters of the SetBinding method can use the most primitive DependencyObject type object to improve universality.
Many WPF controls have encapsulated the SetBinding method, so that when the object is bound to its own property, you can call its own SetBinding method to omit the target parameter.

Compared with Winform, WPF implements the function of saving/retrieving object attributes by attribute name.

How to Implement the method of storing/retrieving object attributes by name in WPF uses the dependency attribute technology, which will be further studied later.

 

What is the magic in the world of programs, but the difference in how much work is done.

The so-called data and display separation, but in addition to the two layers, an additional management organization is created.

The binding technology of WPF is a department in this management organization, responsible for receiving and sending express parcels!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.