[WPF] WPF MVVM simple example

1 New WPF application WPFMVVMExample

The program structure is shown in the following figure.

 

 

2 ModelRealization

Under the Model folder, create a new Business Class StudentModel (Class File StudentModel. cs), and the detailed code for the class is shown below.

using System.ComponentModel;
 
namespace WPFMVVMExample.Model
{
    public class StudentModel : INotifyPropertyChanged
    {
        /// <summary>
        /// School number/// </summary>
        private int studentId;
        public int StudentId
        {
            get 
            { 
                return studentId; 
            }
            set 
            { 
                studentId = value;
                NotifyPropertyChanged("StudentId");
            }
        }
 
        /// <summary>
        /// Full name/// </summary>
        private string studentName;
        public string StudentName
        {
            get 
            { 
                return studentName; 
            }
            set 
            { 
                studentName = value;
                NotifyPropertyChanged("StudentName");
            }
        }
 
        /// <summary>
        /// Age/// </summary>
        private int studentAge;
        public int StudentAge
        {
            get 
            { 
                return studentAge; 
            }
            set 
            { 
                studentAge = value;
                NotifyPropertyChanged("StudentAge");
            }
        }
 
        /// <summary>
        /// Email
        /// </summary>
        private string studentEmail;
        public string StudentEmail
        {
            get 
            { 
                return studentEmail; 
            }
            set 
            { 
                studentEmail = value;
                NotifyPropertyChanged("StudentEmail");
            }
        }
 
        /// <summary>
        /// Sex/// </summary>
        private string studentSex;
        public string StudentSex
        {
            get 
            { 
                return studentSex; 
            }
            set 
            { 
                studentSex = value;
                NotifyPropertyChanged("StudentSex");
            }
        }
 
        public event PropertyChangedEventHandler PropertyChanged;
        public void NotifyPropertyChanged(string propertyName)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
            }
        }
    }
}

StudentModelClass implements the interface INotifyPropertyChanged. When the class implements the interface, it can notify the client performing the binding that a property value has changed.

 

3 ViewModelRealization

Under the ViewModel folder, create a new class file StudentViewModel.cs. The detailed code of the class file is shown below.

using System;
using System.Windows.Input;
using WPFMVVMExample.Model;
 
namespace WPFMVVMExample.ViewModel
{
    public class StudentViewModel
    {
        public DelegateCommand ShowCommand { get; set; }
        public StudentModel Student { get; set; }
        public StudentViewModel()
        {
            Student = new StudentModel();
            ShowCommand=new DelegateCommand();
            ShowCommand.ExecuteCommand = new Action<object>(ShowStudentData);
        }
        private void ShowStudentData(object obj)
        {
            Student.StudentId = 1;
            Student.StudentName = "tiana";
            Student.StudentAge = 20;
            Student.StudentEmail = "8644003248@qq.com";
            Student.StudentSex = "Handsome guy";
        }
 
    }
 
    public class DelegateCommand : ICommand
    {
        public Action<object> ExecuteCommand = null;
        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);
            }
        }
    }
}

In addition to defining the StudentViewModel class, the DelegateCommand class is defined, which implements the ICommand interface.

ICommandThe Execute () method in the interface is used to execute commands, and the CanExecute () method is used to indicate whether the current command is available on the target element, which triggers the CanExecuteChanged event in the interface when this availability changes.

We can assign the command Delegate Command, which implements the ICommand interface, to the Command attribute of the Button (command source), which is owned only by the element that implements the ICommandSource interface, so that the ButtonN is bound to the command.

 

4 MainWindow.xamlRealization

MainWindow.xamlThe interface is shown in the following figure.

MainWindow.xamlThe XAML code of the interface is shown below.

<Window x:Class="WPFMVVMExample.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>
        <Label Content=""School number" Height="28" HorizontalAlignment="Left" Margin="54,23,0,0" Name="labelStudentId" VerticalAlignment="Top" />
        <TextBox Text="{Binding Student.StudentId}" IsReadOnly="True" Height="23" HorizontalAlignment="Right" Margin="0,27,289,0" Name="textBoxStudentId" VerticalAlignment="Top" Width="120" />
        <Label Content="Name " Height="28" HorizontalAlignment="Left" Margin="54,61,0,0" Name="labelStudentName" VerticalAlignment="Top" />
        <TextBox Text="{Binding Student.StudentName}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,65,0,0" Name="textBoxStudentName" VerticalAlignment="Top" Width="120" />
        <Label Content=""Age" Height="28" HorizontalAlignment="Left" Margin="54,94,0,0" Name="labelStudentAge" VerticalAlignment="Top" />
        <TextBox Text="{Binding Student.StudentAge}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,99,0,0" Name="textBoxStudentAge" VerticalAlignment="Top" Width="120" />
        <Label Content="Email" Height="28" HorizontalAlignment="Left" Margin="50,138,0,0" Name="labelStudentEmail" VerticalAlignment="Top" />
        <TextBox Text="{Binding Student.StudentEmail}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,141,0,0" Name="textBoxStudentEmail" VerticalAlignment="Top" Width="120" />
        <Label Content=""Sex" " Height="28" HorizontalAlignment="Left" Margin="57,176,0,0" Name="labelStudentSex" VerticalAlignment="Top" />
        <TextBox Text="{Binding Student.StudentSex}" IsReadOnly="True" Height="23" HorizontalAlignment="Left" Margin="94,180,0,0" Name="textBoxStudentSex" VerticalAlignment="Top" Width="120" />
        <Button Command="{Binding ShowCommand}" Content="Show " Height="23" HorizontalAlignment="Left" Margin="345,27,0,0" Name="buttonShow" VerticalAlignment="Top" Width="75" />
    </Grid>
</Window>

MainWindow.xamlThe backend code is shown below.

using System.Windows;
using WPFMVVMExample.ViewModel;
 
namespace WPFMVVMExample
{
    /// <summary>
    /// MainWindow.xaml Interaction logic/ / / / / / /</summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
            this.DataContext = new StudentViewModel();
        }
    }
}

5 Running program

Run the program and click the display button to bind the data to the interface.

 

 

6 Explain

WPFThe use of MVVM can reduce the coupling between UI display and back-end logic code, that is, when changing the interface, only a small amount of logic code can be modified to achieve, or even do not need to modify.

In WinForm development, we usually directly manipulate the elements of the interface (such as TextBox 1. Text = “aaa”), so that when the interface changes, the back-end logic code needs to be changed accordingly.

Using the data binding mechanism in WPF, when the data changes, the data will notify the occurrence of changes in the interface, without the need to access the interface elements to modify the value, so in the back-end logic code there is no need to operate on or very few elements of the interface.

Using MVVM, you can well cooperate with the WPF data binding mechanism to achieve the separation of UI and logical code, MVVM in the View presentation interface, responsible for page display, ViewModel responsible for logical processing, including the preparation of binding data and commands, ViewModel throughThe DataContext property of View is bound to View and Model is a business model for ViewModel use.

 

Original address: https://blog.csdn.net/yl2isoft/article/details/20838149

Leave a Reply

Your email address will not be published. Required fields are marked *