Binding for WPF Learning (1); binding for wpf Learning

Source: Internet
Author: User

Binding for WPF Learning (1); binding for wpf Learning

The essence of a program is the data plus algorithm. To put it simply, a user gives an input. After algorithm processing, the computer gives an output to the user. We can clearly see that data is dominant in this process. However, when we program a graphical User Interface (GUI), data is always passive. That is to say, the program is always waiting to receive messages/events from the UI. After these events are processed, the program will send a feedback to the user. We can use Data Binding to bring Data back to the core of the program during GUI programming.

1. Status of Data Binding in WPF

We have mentioned before that the essence of a program is Data + algorithm. Data is usually circulated on the storage, logic, and presentation layers. Correspondingly, algorithms are generally distributed in the following areas:

A. Inside the database

B. Read and Write Data

C. Business Logic

D. Data presentation

E. Interaction between interfaces and logic

We can easily understand that the algorithms A and B are generally very stable. We seldom modify them during programming, and their reusability is also very high. C contains a large number of algorithms, because it is most closely related to the customer's needs, which leads to the most complex and changed code. D and E are mainly responsible for the interaction between the UI and logic, as well as corresponding algorithms. Obviously, the C part that contains most of the Code is the most important and the most important part of development, but in our development process, D and E are often the source of trouble. The root cause of the problem is that the status of the logic layer and the presentation layer is not fixed-when we implement the user's needs through programming, it is clear that the logic layer is in a central position, but in the process of UI interaction, the presentation layer is also in the center. As a dedicated display layer technology, WPF helps programmers to focus their thinking on the logic layer at a very level under its gorgeous appearance, the presentation layer is always subordinate under any circumstances. What makes WPF have this "super power? The key lies in the introduction of Data Binding and the Dependency Property and Data Template.

We often say that in WPF development, it is "data-driven UI". What exactly is "data-driven UI? In fact, in WPF programming, Data Binding serves as a highway in real life. With it, the processed Data is automatically transmitted to the user interface for display, data modified by the user will also be automatically uploaded back to the logic layer through him ...... The logic layer of a program is like an engine.

After the Data Binding mechanism is introduced, the logic layer and the presentation layer are directly removed without any logic problems. The advantage of this is that the user interface does not contain algorithms, and Data Binding itself is bidirectional communication, so it is equivalent to combining the two parts D and E into one.

2. Binding Basics

What is Binding? We can regard Binding as a bridge, and its two ends are Source and Target. Where the data comes from, where is the source, and where is the target. Generally, the Binding source is the object at the logic layer, and the Binding object is the control object at the UI Layer. After Binding is implemented, the data is continuously sent from the logic layer to the UI Layer through Binding. The UI Layer displays the data, which completes the UI process driven by data. At the same time, in this process, we can set whether it is two-way communication or one-way communication between the targets, and check the data accuracy or even convert the data type during data transmission.

Next, let's look at the simplest Binding example.

First, create a Student object for use as a data source.

1 class Student2     {        3         private string _name;4         public string Name5         {6             get{return _name;}7             set{_name = value;}8         }        9     }

This class is very simple. It is simple to have only one Name attribute of the string type. As mentioned above, a data source is an object, and an object may have a lot of data, which is exposed to the outside world through attributes. Which element do you want to deliver to the UI element through Binding? In other words, which attribute value does the UI element care about? This attribute value is called the Binding Path ). However, the property does not work. ------- Binding is an automatic mechanism. After the value changes, the property must have the ability to notify the Binding so that the Binding can pass the changes to the UI element. How can we make a property capable of changing the notification Binding value? The method is to trigger a PropertyChanged event in the Set statement of the attribute. We do not need to declare this event by ourselves. What we need to do is to implement the INotifyPropertyChanged interface in the System. ComponentModel namespace as the data source class. When a data source is set for Binding, Binding automatically listens for the PropertyChanged event from this interface.

The class implementing the INotifyPropertyChanged interface looks like this:

1 class Student: INotifyPropertyChanged 2 {3 public event PropertyChangedEventHandler PropertyChanged; 4 private string _ name; 5 6 public string Name 7 {8 get 9 {10 return _ name; 11} 12 13 set14 {15 _ name = value; 16 // trigger event 17 if (PropertyChanged! = Null) 18 {19 this. PropertyChanged. Invoke (this, new PropertyChangedEventArgs ("Name"); 20} 21} 22} 23}

After the upgrade, the PropertyChanged event will be triggered as long as the value of the Name attribute in Student changes, after receiving this event, Binding finds that the event message tells it that the value of the Name attribute has changed, so it notifies the UI element of the Binding target to display a new value.

Now, we prepare a Text and a Button on the form. The Code is as follows:

1 <Window x: Class = "_ constraint binding basics. mainWindow "2 xmlns =" http://schemas.microsoft.com/winfx/2006/xaml/presentation "3 xmlns: x =" http://schemas.microsoft.com/winfx/2006/xaml "4 xmlns: d =" http://schemas.microsoft.com/expression/blend/2008 "5 xmlns: mc =" http://schemas.openxmlformats.org/markup-compatibility/2006 "6 xmlns: local = "clr-namespace: _ constraint binding basics" 7 mc: ignorable = "d" 8 Title = "MainWindow" Height = "110" Width = "300"> 9 <Grid> 10 <StackPanel> 11 <TextBox Name = "txtBoxName" Margin = "5" BorderBrush = "Black"> </TextBox> 12 <Button Content = "Add Age" Click = "Button_Click" Margin = "5"> </Button> 13 </ stackPanel> 14 </Grid> 15 </Window>

Next, we use Binding to connect the data source and UI elements. The specific code is as follows:

1 public partial class MainWindow: Window 2 {3 Student stu; 4 public MainWindow () 5 {6 InitializeComponent (); 7 // prepare the data source 8 stu = new Student (); 9 10 // prepare Binding11 Binding binding = new Binding (); 12 binding. source = stu; 13 binding. path = new PropertyPath ("Name"); 14 15 // use Binding to connect to the data source and Binding target 16 BindingOperations.SetBinding(this.txt BoxName, TextBox. textProperty, binding); 17 18 19} 20 21 private void Button_Click (object sender, RoutedEventArgs e) 22 {23 stu. name + = "Button"; 24} 25}

Next we will explain this piece of code one by one. In the Binding preparation section, use "Binding binding = new Binding ();" to declare the Binding type variable, create an instance, and then use "binding. source = stu; "specifies the Source for Binding and uses" binding. path = new PropertyPath ("Name"); "specifies the access Path for Binding.

The task of connecting the data source and target is completed using the "BindingOperations. SetBinding (...)" method. The three parameters of this method are the focus of our memory:

The first parameter specifies the Binding target. In this example, this. textBoxName is used.

Similar to the Path principle of the data source, the second parameter is used to specify which data is delivered to the target for Binding.

The third parameter is obvious, that is, to specify which Binding instance is used to associate the data source with the target.

Finally, we updated the Name attribute in the Click Event of the Button, run the program, and Click the Button. The following results are displayed:

 

Use this example as the basis. Next we will study every feature of Binding.

 

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.