WPF/MVVM Quick Start Guide (translated)

Source: Internet
Author: User
Tags silverlight

This article was created by Barry Lapthorn, who felt very well written, translated, and made a souvenir. Because the English level is too bad, so the translation is wrong or the translation is not good place please correct me. In addition, since the original text is for WPF, I have made some changes on the basis of the original text so that the example can be run on Silverlight.

Original link: http://www.codeproject.com/KB/WPF/WpfMvvmQuickStart.aspx

Brief introduction

Assuming you have a good understanding of C + + and have a proper understanding of C #, it will not be too difficult to get ready to start learning WPF. I started working on WPF six months ago, and then probably led to a result in Google search, and I finally started to understand and start using WPF for production (did I miss the boat, another story for another day).

As with any new technology, you will benefit from it afterwards, and in my opinion, almost all of the WPF tutorials I have encountered are deficient in the following areas:

    • The examples are all in WPF.
    • The example lacks critical annotations, and in fact you make a much easier
    • Examples try to show off the ability of WPF, a lot of meaningless results, no help for you
    • Some of the class names used in the example appear to be too similar to the Framework keyword or class name, so it is difficult to use them as user-defined identifiers in XAML code (Listboxgroupstyle's name is a headache for beginners).

To solve this problem, I wrote down this article based on the first result I got from the WPF tutorial on Google. This article may not be 100% correct, or even "the only right way" to do things, however it will clarify some of the main points that I wanted to discover six months ago.

I will quickly introduce some topics and then show an example to explain or illustrate each point. So I'm not actually trying to make the GUI prettier, because that's not the point of this article (see above).

Because this tutorial is quite long, for brevity I will omit a lot of code, so please download the attached zip file and look inside the example (. net4.0/vs2010). Each example is based on the previous example.

Basic elements

    1. What WPF is most about is data binding, in short, you have some data that you put in a collection according to a feature, and then you want to show it to the user. You can "bind" the data to XAML code.
    2. WPF has two parts, Xmal describes your GUI layout and effects, and this background code is bound to XAML.
    3. One of the most elegant ways to organize your code in a way that is most likely to be reused is to use the "MVVM" pattern: Model, view, view model.

The key points you need to know

    1. The collection you should use to store the data is observablecollection<>. Not a list, not a dictionary, but a observablecollection. The word "Observable" here is provided for this situation: the WPF window needs to be able to observe your collection of data. This collection class implements several interfaces that are used by WPF.
    2. Each WPF control (including "Windows") has a "DataContext", and the collection control has a "ItemsSource" property for binding.
    3. The "INotifyPropertyChanged" interface will be widely used for communication between the GUI and your code, when there is any change in the data.

Example 1: The wrong approach

The best way to start is to start with an example, starting with a song class, not the usual person class, and we can sort the songs into the album, or a large collection, or sort by the artist. A simple song class should look like this:

View Code

In WPF terminology, this is called "model", and the GUI is "view". The incredible "view model", tied together by data binding, is really a good adapter that can turn a model into something that a WPF framework can use. So just repeat, this is the "model".

Since we created song as a reference type, we can easily create songviewmode because replicas are cheap in memory. The first thing we need to consider is, what is our (potential) need to display? If we only care about the artist name of the song and don't care about the title of the song, then Songviewmodel can define it as follows:

View Code

It's just not quite right. As we expose an attribute in ViewModel, we obviously want to make the artist name of the song changed in the code automatically appear on the GUI, and vice versa:

View Code

Note that in all cases, we have created a "declaration" of the view model, for example, in the XAML code:

View Code

This is equivalent to doing this in the background code MainWindo.cs:

View Code

Then remove the DataContext element from the XAML:

View Code

This is the result of the operation:

Clicking the Update button does not make any updates, as we do not implement data binding.

Data binding

Remember I said at the outset that I would choose a prominent attribute. In this example, we want to show the artist's name. I chose this name because it is not the same as any WPF properties. There are countless examples on the web, choosing a person class and his Name property (which exists in multiple WPF elements), and perhaps the authors of these articles simply don't realize that this is particularly confusing for beginners (the target audience of these articles is curious enough).

There are many other articles about data binding, so I can't include them all. I hope this example is so insignificant that you can see how it is going.

Binding the Artistname property of Songviewmodel, we can do this in Mianwindow.xaml simply:

View Code

The "bind" keyword binds the text of this control, where the control is TextBlock, and the object is returned by DataContext for the "Artistname" property. As you can see above, we have set up a Songviewmodel instance for DataContext, so we are actually showing _songviewmodel.artistname on TextBlock.

Again: Clicking the Update button does not make any updates, as we do not implement data binding. The GUI will not receive any notification of property changes.

Example 2:inotifypropertychanged interface

We have to implement a clever interface named INotifyPropertyChanged. As he says, any class that implements this interface notifies all listeners when a property changes, so we need to modify the Songviewmodel Class A little bit more:

View Code

Now there are a few things happening here. First, we checked to see if we really changed the properties: this would slightly improve performance for most complex objects. Second, if the value has changed, we register the PropertyChanged event with all listeners.

So now we have a model, and a view model. We just need to define the view. You only need to modify MainWindow:

View Code

To test data binding, we can use the traditional method of creating a button and then writing its OnClick event, so the above XAML has a button, and a click event, which gives the backend code:

View Code

That's OK, but we shouldn't use WPF this way: first, we added the "Update Artist" logic in the backend code. It should not belong there. The window class is associated with the open window. The second problem is that if we want to move the logic in the button click event, this will be difficult to control. For example, making a menu item means that we are going to cut, paste, and then edit it in multiple places.

This is the improved view, now click there to work:

Example 3: Command

There is a problem with binding to GUI events. WPF gives you a better way to do that is to icommand the interface. Many controls have a command property. These controls also obey bindings like content and Itemsource, except that you need to bind it to a property and return a ICommand interface. For the trivial example we see here, we have only implemented a class called "Relaycommand" that implements the ICommand interface:

View Code

The ICommand interface requires a user-defined two method: the bool CanExecute method, and the void Execute method. The CanExecute method actually only says to the user, can I execute this command? This is useful for managing the context and you can perform GUI actions. In our case, we don't care about this, so we return true, meaning that the framework can always invoke the "Execute" method. You may have a situation where you have a command bound to a button that can only be executed if you select an item in the list. You may be able to implement this logic in the "CanExecute" method.
Since we want to reuse the code for the ICommand interface, we use the Relaycommand class, which contains all the code that can be reused, and those that we don't want to continue writing.
To show how easy ICommand is to be reused, we have bound a button and a menu item to update the artist command.

View Code

Notice that we no longer bind the button to the specified click event, or the menu specifies the click event.

View Code

Click two buttons to work.

Example 4: Frame

If you have read this article carefully, you may have noticed many duplicate codes so far: Register INPC, or create a command. This is a boilerplate file for most of the code, and for INPC we can move it to a base class to make it easier for us to "Observableobject". For the Relaycommand class, we can move it to our. NET class library. All of the MVVM frameworks (Prism,calibum, etc.) that you find online have started like this.
In terms of the relationship between "Observableobject" and "Relaycommand", they would rather become more basic, and refactoring would be the corollary. It is not surprising that these classes are virtually identical to those written by Josh Smith.

So we move these classes to a small class library so that we can reuse them in the future.

The result looks very similar to the previous:

Example 5: The song collection, the wrong approach

As I have said, you need to use ObservableCollection in order to display the entries in the collection in your attempts (for example, XAML). In this example, we created a albumviewmodel, It is very beautiful to collect our songs together in some things that people can understand. We've also introduced a simple song database, just so that we can generate some song information quickly in this example.

Your first attempt might look like this:

View Code

You might think: "At this point I have a different trying model, and I want to show these songs as a albumviewmodel instead of Songviewmodel".

We also create some more commands and attach them to some buttons:

View Code

In this example, clicking "Add Artist" will work fine, but clicking on "Update artist name" will not work. If you read a yellow highlighted comment on the MSDN page, it explains this:

In order to fully support data values from the bound data source object passed to the binding target, each object in your collection, which supports bindable properties must implement an appropriate property change notification mechanism, such as the INotifyPropertyChanged interface.

Our view looks like this:

Example 6: The song Collection, the right procedure

In this last example, we install Albumviewmodel on a ObservableCollection songviewmodels so that we can create it more easily:

Now that all of our buttons are bound to the command to manipulate our collection, our backend code MainWindow.cs is still very clean.

Our view looks like this:


Conclusion

Instantiate your view model

Finally, it's worth mentioning that when you declare your view model in XAML, you can't pass any arguments to it: in other words, your view model must have a
An implicit or displayed default constructor. How many states are added to the view model is entirely up to you, and you may find it easier to declare the view model in the Mainwindow.cs backend code, where you can pass the construction parameters.

Other frameworks

There are many other MVVM frameworks with different complexities and features, and they target either wpf,winpho7,silverlight or any combination of these three.

At last..

Hopefully these 6 examples will show you how simple it is to write a WPF application using MVVM, and I'm trying to cover all the points that I think are important and often discussed in many articles.

If you find this article useful, please vote.

If you find an error in this article, or if I say something wrong, or if you have some other questions about this article, please leave a comment below to explain why and how you adapted to him.

Reference

I have complied with all kinds of articles when I write this article. NET Programming Guide conventions and styles. The list of references I used to write this article is listed here:

      1. Effective C #
      2. Framework Design guidelines:conventions, idioms, and Patterns for reusable. NET Libraries
      3. C # 4.0 in a nutshell:the definitive Reference
      4. WPF 4 Unleashed
      5. Josh Smith

WPF/MVVM Quick Start Guide (translation) (RPM)

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.