WPF Classic Programming Mode-MVVM Sample Tutorial

Source: Internet
Author: User

One, MVVM theory knowledge

From the previous article, we already know that the main feature of WPF technology is data-driven UI, so in the process of developing with WPF technology is data-centric, WPF provides a data binding mechanism, and when data changes, WPF automatically notifies you to update the UI.

We use patterns that are generally wanted to achieve high cohesion and low coupling. In WPF development, the classic programming paradigm is MVVM, a model tailored to WPF that leverages WPF's data-binding mechanisms to minimize the coupling of xmal files and CS files, which is the coupling between UI display and logic code, if the interface needs to be replaced. There is little or no modification to the logic code. Compared with WinForm development, we typically use the name of the control in the post code to manipulate the control's properties to update the UI, whereas in WPF the UI is usually updated through data binding, and in response to user actions, WinForm is handled by the control's events. WPF can be handled in a way that uses command bindings, and the degree of coupling is reduced.

We can intuitively understand the MVVM pattern by:

View is a XAML-implemented interface that is responsible for interacting with the user, receiving input from the user, and presenting the data to the user.
ViewModel, a C # class, collects data and commands that need to be bound, aggregates model objects, binds to view through the DataContext property of the view class, and can handle some UI logic.
Model, which is the object in the system, can contain properties and behaviors.

In general, the view corresponds to a viewmodel,viewmodel can aggregate n Model,viewmodel can correspond to multiple view,model do not know the existence of view and ViewModel.

Second, the MVVM example explains

This example is intended to give you a visual understanding of the programming patterns of MVVM, the data bindings and commands used in them, which are discussed later in this article.

    1. First define the Notificationobject class. The purpose is to bind data properties . The function of this class is to implement the INotifyPropertyChanged interface. In WPF, the class wants to implement this interface, and its property members have the ability to notify the UI, the knowledge of data binding, discussed in detail later.
Using System.componentmodel;namespace wpffirst{    class notificationobject:inotifypropertychanged    {        public event PropertyChangedEventHandler propertychanged;        public void raisePropertyChanged (String propertyname)        {            if (this. propertychanged = null)            {this                . PropertyChanged (This, new PropertyChangedEventArgs (PropertyName));}}}    

2. Define the Delegatecommand class. The purpose is to bind the command property . The purpose of this class is to implement the ICommand interface, a class that implements the ICommand interface in WPF to bind to the UI as a command. The knowledge of the command is discussed in detail later.

Using system;using system.collections.generic;using system.windows.input;namespace wpffirst{class delegatecommand:i        Command {//a method prototype without return value.        Public action<object> ExecuteCommand = null;        A method prototype return a bool type.        Public Func<object, bool> canexecutecommand = null;        public event EventHandler Canexecutechanged; public bool CanExecute (object parameter) {if (Canexecutecommand! = null) {RE Turn this.            Canexecutecommand (parameter);            } else {return true; }} public void, Execute (object parameter) {if (this. ExecuteCommand! = null) this.        ExecuteCommand (parameter);                } public void Raisecanexecutechanged () {if (canexecutechanged! = null) {            Canexecutechanged (this, eventargs.empty); }        }    }}

3. Start defining the Model class. A property member "WPF", which is the data property, has the notification function, which changes after it notifies the UI update. A method of "Copy", which alters the value of the property "WPF", is the corresponding UI event in the manner of the command.

Using system.componentmodel;using system.windows.input;namespace wpffirst{    class Model:notificationobject    {        private string _wpf = "WPF";        public string WPF        {            get {return _WPF;}            Set            {                _WPF = value;                This. raisePropertyChanged ("WPF");            }        }                public void Copy (object obj)        {this            . WPF + = "WPF";}}}            

4. Define the ViewModel class. Defines a command attribute "Copycmd", which aggregates a model object "model". The key here is that the method of specifying the response command to the Copycmd command is the "Copy" method of the Model object.

Using System;namespace wpffirst{    class ViewModel    {public        delegatecommand copycmd {get; set;}                Public model model {get; set;}        Public ViewModel ()        {            This.model = new Model ();            This. Copycmd = new Delegatecommand ();            This. Copycmd.executecommand = new action<object> (this.model.Copy);}}    

5. Define the view.

MainWindow.xaml code: We can see that the Text property of the TextBlock control is bound to the WPF property of the Model object; The button's Click event is bound to the Copycmd command property through a command.

<window x:class= "Wpffirst.mainwindow"        xmlns= "Http://schemas.microsoft.com/winfx/2006/xaml/presentation"        xmlns:x= "Http://schemas.microsoft.com/winfx/2006/xaml"        Title= "MainWindow" height= "width=" 525 ">    <Grid>        <stackpanel verticalalignment=" Center " >            <textblock text= "{Binding model. WPF} "height=" 208 "textwrapping=" Wrapwithoverflow "></TextBlock>            <button command=" {Binding copycmd} "Height=" width= "232" >Copy</Button>        </StackPanel>    </Grid></Window>

MainWindow.xaml.cs Code: Its working knowledge assigns the ViewModel object to the DataContext property, and the data source of the specified view is the ViewModel.

Using System.windows;namespace wpffirst{    //<summary>//Interaction logic for MainWindow.xaml    // /</summary> public    partial class Mainwindow:window    {public        MainWindow ()        {            InitializeComponent ();            This. DataContext = new ViewModel ();}}    }

6. Run the results. Whenever we click the button, the interface is updated because the Copy method changes the value of the WFP property.

Writing this simple example is to visually understand the programming patterns of MVVM. In actual development, no matter how complex the program is, it adds model, View, ViewModel, and other auxiliary classes (Helpers or Services), and the pattern does not change.

WPF Classic Programming Mode-MVVM Sample Tutorial

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.