Mvvm is mainly for LogicCodeSeparated from the view, so that codebehind only contains operations on the UI. Through Binding and command
The following is a simple example. click the button to add the age to 1.
XAML code
<Window X: class = "deepxaml. mainwindow "xmlns =" http://schemas.microsoft.com/winfx/2006/xaml/presentation "xmlns: x =" http://schemas.microsoft.com/winfx/2006/xaml "xmlns: Local =" CLR-namespace: deepxaml "xmlns: SYS =" CLR-namespace: system; assembly = mscorlib "xmlns: CL =" CLR-namespace: system. collections; assembly = mscorlib "Title =" mainwindow "Height =" 250 "width =" 450 "> <stackpanel> <textbox text =" {binding Path = Name} "> </textbox> <textbox text = "{binding Path = age}"> </textbox> <button command = "{binding Path = addage}"> Add age </button> </stackpanel> </WINDOW>
Mainpageviewmodel
Public class mainpageviewmodel: inotifypropertychanged {public event propertychangedeventhandler propertychanged; private string name; Public string name {get {return name;} set {name = value; If (this. propertychanged! = NULL) {This. propertychanged. invoke (this, new propertychangedeventargs ("name") ;}} private int age; Public int age {get {return age ;}set {age = value; If (this. propertychanged! = NULL) {This. propertychanged. Invoke (this, new propertychangedeventargs ("Age") ;}} public icommand addage {get {return New addagecommand (this );}}}
Public class addagecommand: icommand {private mainpageviewmodel mmainpageviewmodel; Public addagecommand (mainpageviewmodel model) {parameters = model;} public bool canexecute (object parameter) {return true;} public event eventhandler canexecutechanged; public void execute (object parameter) {This. mmainpageviewmodel. age + = 1 ;}}
We can check that there are only a few codes in the background:
Public partial class mainwindow: window {public mainwindow () {initializecomponent (); mainpageviewmodel = new mainpageviewmodel {age = 20, name = "Jack"}; this. datacontext = mainpageviewmodel ;}}