"Layman's language WPF" learning summary of Binding

I. Introduction

  Friendly graphical user interface (Graphics User Interface, GUI) in the last ten years is the popular thing, before the application interaction with the user through the console interface (Console User Interface, CUI) completed. The graphical user interface of the operating system begins in China should be popular from the beginning of the official release of Windows 95, immediately dubbed Visual development tools (as well as Borland's number of similar products) followed emerge. I remember that time hardware to run up has been pretty good Windows 95 - the graphical interface is very consuming hardware resources.

  GUI as a novelty, of course, has become the focus of both the operating system or hardware manufacturer manufacturers concerned. Let us put aside the hardware aside a single operating system developers say, is Microsoft. Windows GUI running mechanism is to use a message (Message) to drive forward the program is running. The main source of the message is the user's operation. For example, clicking the mouse, pressing the button will generate a message, the message will be translated and delivered to the target Windows program is then processed by the program. It sounds and no impact to application software development methodology. In order to write GUI programs that run on Windows, various development methodologies is also the basic principles of this "Drivers" must follow. It is along this road development, only the Windows API developed purely event-driven, message-driven MFC and so have the C ++ class library, only to start Visual Basic .Net Framework event-driven - in a word , the program is event (i.e., the encapsulated message over) from the UI driven forward. Referred to as the "message-driven" or "event-driven." Because the message or event mostly from UI, they all collectively referred to as "UI Drivers"

  Message-driven or event-driven itself is not wrong, but on a higher level, the use of "UI Driver" development program is "to GUI and GUI", in order to achieve a simple GUI programming, in fact, it has deviated from the nature of the program - data + algorithm. While forcing programmers put a lot of focus is on the realization of the UI program. It's not finished. With the growing complexity of programs, codes, and code for processing data for the logic on the UI level intertwined gradually become difficult to maintain. To avoid such problems, a summary of programmers Model-View-Controller (MVC) and Model-View-Presenter (MVP) and many design pattern to separate UI related code and data logically related code.

  Let's go back to basics program. The nature of the data + algorithm program, a user input fed through a feedback algorithm processing program output - here, the core of the data in the program. Anti so far as to see "UI Driver", the data in a passive position, always waiting for the program after receiving a message from the UI / event handling algorithms or after the completion of processing and display. How in the GUI programming to position data from passive to active core, so that the data in the program? This uses the Data Binding

Two, Data Binding position in WPF

  If an application is seen as a city, then the traffic inside the city must be very busy, but the steady stream of pedestrians and vehicles but not the data. In general, the application will have a three-layer structure, i.e., the data storage layer, data processing and data presentation layer. The storage layer corresponds to a storage area of ​​a city, there are system configuration database and file; treatment layer (logical layer) related to the service logic, the algorithm for processing the data are concentrated here, this layer corresponds to urban industrial areas; presentation layer function is to display data processed by the visual interface to the user interface or through other kinds of display to other applications (interface and interfaces are two words in the English language interface, so there is no difference in essence) also need to collect the user's operation, put them back to the logical layer, this layer is equivalent to the city's port area.

  If we are a mayor, we need to be responsible for the city's layout and development - storage areas, industrial park and port area, how can we invest it? Much effort to develop? How should each inside the park development at each park? How traffic between several districts planning to clean highly efficient? How to leave room for future expansion ... These are issues that we consider the fact that these architects do!

  The essence of the program is the data + algorithm. The data storage, logic, and shows three of the laminar flow, so standing on the data perspective, the three layers are important. But the distribution algorithm in the program is not uniform, and for a three-tier program, the algorithm is generally distributed in all those places:

  • A, internal database.
  • B, read and write back to the database.
  • C, the business logic.
  • D, the data show.
  • E, and interface logic.

  A, Part B, two algorithms are generally stable, not easily to change, reusability is also high; C in the most close customer relationships, most complex, change is also the largest, most algorithms are concentrated here; D, E interaction is responsible for two UI and logic, but also occupy a certain algorithm.

  C is obviously part of the core program is the development a top priority, so we should concentrate in the C section. However, D, E in two parts but often a source of trouble. First, both are closely related to the logical layer, we believe it can be able to present the logic layer in the algorithm written in two parts (so only the MVC, MVP and other models to avoid this situation); secondly , the two parts so as to communicate with the logical event messages or layer, upon needs to occur when the same data multiple display / edit, the synchronization code used will be complicated; D and E are present and finally the pair is reciprocal but they need separate write - write an algorithm to display data, modify data is an algorithm. In summary result is two parts D and E will take up part of the algorithm, may also involve a lot of energy.

  Root of the problem is that the status logic layer and the presentation layer is not fixed - when implementing customer demand, the logical layer indeed at the center position, but by the time the presentation layer and interactive UI implementation is central. WPF as a special presentation layer technology, beautiful appearance and only his animated surface phenomena, it is more important to help programmers at a deeper level the thinking center of gravity is fixed in the logic layer, presentation layer never let a subordinate logical layer status, WPF has a key to this capability is the introduction of Data Binding concept and its accompanying Dependency Property system and DataTemplate.

  After migrating from the traditional Windows Form to WPF, for a three-tier program, the data storage layer to build the database and file system. Data transmission and processing still use .Net ADO.NET Framework of the basic classes (as with the Windows Form and other development), the presentation layer using WPF library to achieve, and communication logic layer and the presentation layer is to use the Data Binding to achieve. Visible, DataBinding in WPF play system is the role of the data highway. With this highway, processed data is automatically delivered user interface to be displayed, the modified user data is automatically passed back to the logical layer, once the data is processed will be better served user interface program ... logical layer is like a powerful engine kept running out to show text, graphics, animation and other forms of data processed by the driver user interface - this is the "data-driven UI".

  Data Binding mechanism introduction, D, E will simplify a lot of two portions. First of all, the logical data between the user interface layer "go straight" does not relate to the issue logic, so that almost no portion of the user interface contains an algorithm; Data Binding itself is two-way communication, it is equivalent to the combined D and E; for a plurality of UI elements concerned with a case of data, only need to use data Binding to these UI elements eleven (star-shaped structure with data-centric) associated with the data, when the data changes in these UI elements will simultaneously display the change. So we mentioned earlier the problem is solved. More importantly, after such optimization, all associated business logic algorithms in the data layer, a logical layer becomes a separate operation, the complete system, the user interface layer not contain any code, completely dependent and dependent in data logic level. This has two obvious benefits, first, if the application is seen as the UI layer "skin", the storage layer and logic as a "flesh" program, then we can easily from the skin of the flesh tear off and replaced with a new one; second, because the data layer is capable of independent operation, self-contained, so we can better unit tests without recourse UI test automation tool - you can totally imagine a unit test code "invisible UI", unit testing just use the "UI" to bypass the real test business logic directly UI nothing.

Three, Binding foundation

  If the Binding ratio bridge for data, then he is Binding of both ends of the source (Source) and the destination (Target) data came from, where is the source, Binding is a bridge in the middle of the frame, Binding goal is to go to the data where to go (so we want the bridge to where). In general, the source object Binding logical layers, the control object is a target UI Binding layer, so that a steady stream of data is delivered through UI Binding layer, presentation layer is UI, data-driven process is finished UI. We can imagine this bridge on Binding laying the highway, we can not only control the road is two-way traffic between the primary goal is a one-way direction, you can also control the timing of the release of the data, you can even set up some of the bridge. " Level "for converting the data type or check data accuracy.

   After Binding with the basic concepts of image, let's look at a basic example. This simple example is to create a data source and it is connected by Binding to UI elements.

  First, we create a class called Student, instances of this class will be used as a data source.

 1     public class Student
 2     {
 3         private string _name;
 4 
 5         public string Name
 6         {
 7             get { return _name; }
 8             set { _name = value; }
 9         }
10 
11     }

  Student can see this class is very simple, so simple that only a Name property of type string, as I said before, the data source is an object, a subject who may have a lot of data, which they attribute by exposure to the outside world, then that which data is you want to be served by Binding UI elements of it? In other words, the UI elements on which interest is to change the property value of it? This property has become the path of Binding (Path). Yet, if property is not enough --Binding is an automatic mechanism, when the attribute properties have the ability to change the notification Binding, Binding to make changes passed to the UI elements. How can I make such a property have the ability to notify the Binding values ​​have to change it? The method is planning a ProertyChanged event attribute set statement. This event does not need to affirm ourselves, we have to do is to make the class as a data source implement the INotifyPropertyChanged Interface System.ComponentModel namespace. After setting up a data source for Binding, Binding will automatically listen PropertyChanged events from this interface.

  Student class implements INotifyPropertyChanged interface looks like this:

 1 public class Student : INotifyPropertyChanged
 2 {
 3     private string _name;
 4 
 5     public string Name
 6     {
 7         get { return _name; }
 8         set
 9         {
10             _name = value;
11             if (PropertyChanged != null)
12                 PropertyChanged(this, new PropertyChangedEventArgs("Name"));
13         }
14     }
15 
16     public event PropertyChangedEventHandler PropertyChanged;
17 }

  After such an upgrade, when the value of the Name property changes PropertyChanged event is fired. Binding event was found after receiving the news of this event it called Name property value has changed, then it will notify the UI elements Binding target side displays the new value.

  Then, we prepare a TextBox and a Button on the form. Binding the TextBox as a target, we will change the Name property values ​​Student object when the Button Click event.

 1 <Window x:Class="WpfApp2.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:WpfApp2"
 7         mc:Ignorable="d"
 8         Title="MainWindow" Height="110" Width="300">
 9     <StackPanel>
10         <TextBox x:Name="txtBoxName" Margin="5" BorderBrush="Black"/>
11         <Button Content="Test" Margin="5" Click="Button_Click"/>
12     </StackPanel>
13 </Window>

   Next, we will be the most important step - to use Binding data source and UI elements are connected, as follows

 1 public partial class MainWindow : Window
 2 {
 3     Student mStdTest;
 4     public MainWindow()
 5     {
 6         InitializeComponent();
 7 
 8         mStdTest = new Student();
 9 
10         var binding = new Binding("Name") { Source=mStdTest};
11         BindingOperations.SetBinding(txtBoxName, TextBox.TextProperty, binding);
12     }
13 
14     private void Button_Click(object sender, RoutedEventArgs e)
15     {
16         mStdTest.Name += "Name";
17     }
18 }

   Let us one by one interpretation of what this code: This code is part of the background Windows1 class, which is part of the UI XAML code given above. "Student mStdTest" is a statement of a member variable of type Student is Windows1 class, the aim is to be able to access Student instance (data source) by its referenced in the constructor and Windows1 Button_Click event handler.

  In the constructor Windows1 "InitializeComponent ();" it is automatically generated code, use the initialization UI elements. "MStdTest = new Student ();" The message is to create an instance of a Student types and reference it with mStdTest member variables, this example is our data source.

  The portion preparing Binding, first with "Binding binding = new Binding (" Name ") {Source = mStdTest};" declared type Binding variable and instantiate it, and in the constructor and the constructor set inside Path (access path) and source (access the source).

  Task data source and destination are connected together using the "BindingOperations.SetBinding (...);" Method completed. Three parameters of this method is the focus of our memories.

  1. The first parameter specifies Binding of the target, in this case txtBoxName.
  2. Path principle similar to the data source, the second parameter is used to indicate which attributes Binding data delivery target. But you will find that property here is not an object but rather with the class of a static read-only (Static Readonly) dependency property. In fact well understood that the values ​​of such properties may be dependent on the Binding attribute values ​​of other objects, it is driven by another object property value.
  3. The third argument is very clear, which is to specify the Binding instance to associate the data source and the target.

  In the end Button_Click ... Button element method is click event in his inside our Name attribute data sources have been updated. Run the program, when you click Button, TextBox will instantly display updated value of the Name property as follows:

  In practice, the code may be implemented Binding seen above are not the same, because the base class FrameworkElement TextBox of UI elements such BindingOperations.SetBinding (...) method of the package, the package is also called SetBinding result, only parameter changes, as follows:

1 public BindingExpressionBase SetBinding(DependencyProperty dp, BindingBase binding)
2 {
3     return BindingOperations.SetBinding(this, dp, binding);
4 }

  By the above example, we have established the following model in mind

 

Guess you like

Origin www.cnblogs.com/insipid/p/12232187.html