This is just my study notes. Please refer to the original author for your study.
Refer to learning video: https://www.bilibili.com/video/av40886206/
Refer to learning blog: https://www.cnblogs.com/wzh2010/p/6285990.html
1. Use MVVMLight in the project
[1.1] search for MVVMLight in Nuget
[1.2] after adding, there will be more files
After completion, there will be an additional ViewModel folder containing the following two files:
MainViewModel.cs
ViewModelLocator.cs
In addition, app Add ViewModelLocator as a resource to the global application in XAML In resources:
[1.3] If an error is reported, it is caused by naming and referencing the namespace. The solution:
2,Model,View,ViewModel,
First, create a directory with a complete three-tier structure, as shown in the figure, including three-tier folders of Model, View and ViewModel:
[2.1]Model
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GalaSoft.MvvmLight;//Add reference namespace WPF_MVVMLight.Models { public class StudentModel: ObservableObject//Add and inherit this ObservableObject class (observable class) { private int id; public int Id { get =>id; set { id = value; RaisePropertyChanged(()=>Id); } } private string name; public string Name { get => name; set { name = value; RaisePropertyChanged(() => Name); } } } }
[2.2] ViewMedol: interact with View
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using GalaSoft.MvvmLight; using WPF_MVVMLight.Models; namespace WPF_MVVMLight.ViewModel { public class StudentViewModel : ViewModelBase { public StudentViewModel() { if (IsInDesignMode) //If it is design mode { StudentModel=new StudentModel(){Id=1,Name = "Zhang San"}; } else//Operation mode { //Simulate fetching data from database StudentModel = new StudentModel() { Id = 2, Name = "Li Si" }; } } public Models.StudentModel StudentModel { get; set; } } }
[2.3] VIew: display and interactive ViewModel
Label Content is bound to StudentModel Id and Name properties, so the label should display the Id and Name properties of the StudentModel object
At this time, the ViewModel has nothing to do with the View, so we write the following code in the View constructor:
3. Constructor
[3.1]
So every time the App initializes, it initializes the ViewModelLocator class.
[3.2] register StudentViewModel instance
[3.3] in View: delete the code of the new object