WPF MVVM

This article discusses the MVVM pattern from two aspects:

  1. MVVM theoretical knowledge
  2. MVVM example explanation

 

1. MVVM theoretical 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 using WPF technology, data is the core, WPF provides a data binding mechanism, when the data changes , WPF will automatically send a notification to update the UI. 

  We use patterns, generally to achieve high cohesion and low coupling. In WPF development, the classic programming mode is MVVM, which is tailored for WPF. This mode makes full use of the data binding mechanism of WPF and minimizes the coupling between Xmal files and CS files, that is, UI. The coupling between the display and the logic code, if the interface needs to be changed, the logic code is modified very little or not. Compared with WinForm development, we generally use the name of the control in the post code to manipulate the properties of the control to update the UI, while in WPF, the UI is usually updated through data binding; in response to user operations, WinForm is through Control events to handle, and WPF can use the command binding method to handle, the coupling will be reduced.

  We can intuitively understand the MVVM pattern through the following figure:  

  View is an interface implemented with xaml, responsible for interacting with users, receiving user input, and displaying data to users.
  ViewModel, a C# class, is responsible for collecting data and commands that need to be bound, aggregating Model objects, binding to View through the DataContext property of the View class, and also handling some UI logic.
  A Model is an object in the system that can contain properties and behaviors.

  Generally, a View corresponds to a ViewModel, a ViewModel can aggregate N Models, and a ViewModel can correspond to multiple Views. The Model does not know the existence of View and ViewModel.

Second, MVVM example explanation

  This example is to let everyone intuitively understand the programming mode of MVVM. The knowledge of data binding and commands used in it will be discussed in the following articles.

  1. First define the NotificationObject class. The purpose is to bind data properties . The role of this class is to implement the INotifyPropertyChanged interface. Classes in WPF must implement this interface, and their property members have the ability to notify the UI and the knowledge of data binding, which will be discussed in detail later.
copy code
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));
            }
        }
    }
}
copy code

  2. Define the DelegateCommand class. The purpose is to bind command properties . The role of this class is to implement the ICommand interface. The class that implements the ICommand interface in WPF can be bound to the UI as a command. Knowledge of commands is discussed in detail later.

copy code
using System;
using System.Collections.Generic;
using System.Windows.Input;

namespace WpfFirst
{
    class DelegateCommand : ICommand
    {
        //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)
            {
                return 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);
            }
        }
    }
}
copy code

  3. Start defining the Model class. A property member "WPF", which is a data property, has a notification function. After it changes, it will know to notify the UI update. A method "Copy" is used to change the value of the property "WPF", which corresponds to UI events by means of commands.

copy code
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";
        }
        
    }
}
copy code

  4. Define the ViewModel class. A command attribute "CopyCmd" is defined, which aggregates a Model object "model". The key here is that the way to specify the response command to the CopyCmd command is the "Copy" method of the model object.

copy code
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);
        }
    }
}
copy code

  5. Define 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 click event of the Button is bound to the CopyCmd command property through the command.  

copy code
<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="350" Width="525">
    <Grid>
        <StackPanel VerticalAlignment="Center" >
            <TextBlock Text="{Binding model.WPF}" Height="208" TextWrapping="WrapWithOverflow"></TextBlock>
            <Button Command="{Binding CopyCmd}" Height="93" Width="232">Copy</Button>
        </StackPanel>
    </Grid>
</Window>
copy code

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

copy code
using System.Windows;

namespace WpfFirst
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            this.DataContext = new ViewModel();
        }
    }
}
copy code

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

  This simple example is written to intuitively understand the programming pattern of MVVM. In actual development, no matter how complicated the program is, that is, adding Model, View, ViewModel, and some other auxiliary classes (Helpers or Services), the mode will not change.

Source: https://www.cnblogs.com/bcsj/archive/2012/11/14/WPF.html

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325208022&siteId=291194637