WPF Tutorial: mvvm mode understanding and application

Source: Internet
Author: User
I, What is mvvm mode?

Mvvm is short for Model-View-viewmodel. Microsoft's WPF brings new technical experiences, such as Silverlight, audio, video, 3D, and animation ....... This makes the software UI Layer more detailed and customizable. At the technical level, WPF also brings new features such as binding, Dependency Property, routed events, command, datatemplate, and controltemplate. The origin of the mvvm (Model-View-viewmodel) Framework is a new architecture framework that evolved from the combination of the Model-View-presenter model and WPF. It is based on the original MVP framework and integrates the new features of WPF to cope with the increasingly complex demands of customers.

Ii. Why mvvm mode?

The mvvm mode solves the problem of communication between model and view in daily development, such as extra operations such as conversion type.

I remember a few years ago when I came into contact with the MVC design model, I felt that the work and presentation between the front-end and backend were so orderly. During development and expansion, you only need to add a new view, a new model, and the corresponding controller code. It is really easy to develop and maintain later stages.

I developed a software system with WPF a few months ago. This system is a summary of the use of WPF technologies. However, no mode is introduced. After development, a large amount of content is accumulated in the XAML and the CS code after the XAML. During maintenance, You need to locate the code by clicking the control area in the design window, locate the background event through the code, and find the processing method through the background event, this long string of coupling traps that are difficult to separate. The XAML of each page is accumulated to a maximum of thousands of lines, and thousands of lines of CS code in the backend are difficult to maintain. At the same time, there are also many immutability issues during development and expansion.

Later, I found many instances on the Internet, and mvvm came into my eyes first. This mode absorbs the essence of the MVC mode and has specific implementation methods for WPF, so that the code can be organized in an orderly manner.

1. demonstrate how mvvm is organized.

Figure 1

The following figure shows the implementation relationship of the mvvm mode. In development, view integrates user operations and data presentation methods. To a large extent, two problems exist in writing code directly:

1. The data types of many controls in the view are different from those in the model. For example, in development and gender, a bool type variable may be placed in the model. However, in the front-end display view, the user should see "male" and "female ". This requires a conversion. Is this conversion in view? The logic code should not appear on the interface. In model? Not suitable. This will lead to more attributes and methods, resulting in a bloated model.

2. in WPF development, events and commands can make a UI work normally. We know that winform is event-driven. Therefore, it is easier to understand and implement events. However, the problems are the huge and diverse events in the later stage. These events cannot be reused? No.

These two problems generate a secondary role viewmodel between the model and view. It needs to help the view to convert the corresponding data to the model or to the content that the view can display from the model. At the same time, it also needs to bind multiple view commands to the processing methods in the model. These commands can be reused. When other views need them, they can also call the method bound to the command. Viewmodel can be regarded as a variant controller.

Iii. Implementation Principle

Solved the two problems raised in the previous section, and actually solved all the working principles of viewmodel.

First, start with the binding issue. The control in the view has an attribute called "datacontext ". This is the source of control data usage. The datacontext attribute specifies a background model for the control so that the data used by the control comes from this model class. Therefore, viewmodel should act as the background model and provide display data for the view control. At the same time, the viewmodel data should be provided by the model behind it. Therefore, in brief, the viewmodel is defined based on the data displayed in the view. For example, if a view constructs a textblock control, you only want to display a string in the model. In viewmodel, we should reference the model here. As a view part, we can call a string attribute of this model. For example, if a listview is built in the view, a series of product names are displayed. For a model, each instance is a product. Viewmodel should be a set of models, which stores all the model sets that need to be displayed by listview.

Second, solve the command problem. The class routedcommand and routeduicommand that implement icommand have been built in WPF. For different view events, which one is used independently is not a full solution. Therefore, you need to define a class that implements the icommand interface. Currently, there are two solutions on the Internet: delegatecommand and relaycommand. All of them have the icommand interface, and different processing methods can be bound to different events. The difference is: I) delegatecommand uses a raisecanexecutechanged method and requires developers to manually trigger the control to execute judgments. In relaycommand, the agent determines the trigger here to commandmanager. More convenient; ii) delegatecommand is manually controlled by developers, so resource usage is low, and relaycommand needs to be determined when various commands are triggered. Therefore, the resource usage is relatively high. This is especially reflected in complicated systems. So it depends on the developer's choice. Of course, you can also manually write some xxxcommand that is more suitable for you. The implementation principle is to implement the icommand interface. In addition, the delegate method is used to delegate execute without return values to action, while canexecute with return values to func.

IV. Implementation Process

As mentioned above, you must practice it to deeply understand mvvm.

Here we use the previous product list as the background. The view interface shows a listview to display a list. There is a button below, click a product in the list, and then click the button below to increase the product price by 1 RMB. The interface is shown in the following figure:


When an item is selected, click "Add 1 $", and then the item will add 1 RMB. (The dollar sign is displayed because of the local regional settings and can be changed. This is not described here ).


Well, the following is an example.

First, observe the structure of my example:


Each file here provides a description:

Milk. CS is a model that contains information about the product, such as ID, type, and price.

Notificationobject. CS is actually a public class. The method provided by notifobject object. CS is to remind the foreground to automatically update the numeric attribute to update the numeric value when necessary.

Milklistviewmodel. cs this is a viewmodel. Here we have prepared an observablecollection for the foreground list and provided command binding support for the foreground. Simply put, it instantiates a certain method of preparing for the commodity set into a command type attribute, providing binding for the foreground.

Relaycommand. CS is an icommand interface implementation widely used in mvvm implementation on the Internet. The principle has been mentioned before, and the source code of delegatecommand. CS is also available on the Internet. They are very easy to use.

Mainwindow. XAML acts as a view here, and various UIS for displaying products are arranged. Use binding to bind data sources and commands. However, it should be noted that the data and method commands of the viewmodel can be bound only when datacontext is a viewmodel written.

Here we will not post the code. The principle tells us that everyone can find a perfect solution. If you are interested in the study, you can download the sample program uploaded from my resources (for vs2010 ). You are welcome to study and raise valuable questions. Support originality. For reprint, please indicate the source.


WPF Tutorial: mvvm mode understanding and application

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.