Mvvmlight Practice 3 for UWP development: simple MVVM instance Development (graphic details and code payment ),
Before comparing various MVVM frameworks, I think it is better to make a simple MVVM implementation case by myself. In this way, we can see the inconvenience during implementation. How can various frameworks solve these problems.
1. Create a UWP Empty Project
Using System; using System. componentModel; using System. runtime. compilerServices; namespace MvvmDemo. common {/// <summary> /// Viewmodel base class, two-way attribute binding base /// </summary> public class ViewModelBase: INotifyPropertyChanged {public event PropertyChangedEventHandler PropertyChanged; /// <summary> /// notification of property change /// </summary> /// <param name = "propertyName"> attribute name </param> public void policypropertychanged ([CallerMembe RName] String propertyName = "") {if (PropertyChanged! = Null) {PropertyChanged (this, new PropertyChangedEventArgs (propertyName ));}}}}
4. Create a Command base class
The Code is as follows:
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; using System. windows. input; namespace MvvmDemo. common {public class DelegateCommand <T>: ICommand {// <summary> /// Command // </summary> private Action <T> _ Command; /// <summary> /// determine whether the command can be executed /// </summary> private Func <T, bool> _ CanExecute; /// <summary> /// notification command execution after judgment can be executed /// </summary> pub Lic event EventHandler CanExecuteChanged; /// <summary> /// constructor /// </summary> /// <param name = "command"> command </param> public DelegateCommand (Action <T> command): this (command, null) {}/// <summary> /// constructor /// </summary> /// <param name = "command"> command </param> /// <param name = "canexecute"> command executable judgment </param> public DelegateCommand (Action <T> command, func <T, bool> canexecute) {if (command = null) {throw new ArgumentException ("command");} _ Command = command; _ CanExecute = canexecute ;} /// <summary> /// Command Execution judgment /// </summary> /// <param name = "parameter"> data judgment </param> // <returns> result (True: executable, False: not executable) </returns> public bool CanExecute (object parameter) {return _ CanExecute = null? True: _ CanExecute (T) parameter );} /// <summary> /// Execute the command // </summary> /// <param name = "parameter"> parameter </param> public void Execute (object parameter) {_ Command (T) parameter );}}}
5. Create a ViewModel
The Code is as follows:
Using MvvmDemo. common; using MvvmDemo. models; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace MvvmDemo. viewModels {public class MainViewModel: ViewModelBase {private string _ userId; private string _ userName; private DelegateCommand <string> _ loginCommand; /// <summary> /// user name /// </summary> public string UserId {get {return _ UserId;} set {_ userId = value; yypropertychanged ();}} /// <summary> /// UserName /// </summary> public string userName {get {return _ userName;} set {_ UserName = value; notifyPropertyChanged () ;}/// <summary> /// logon command /// </summary> public DelegateCommand <string> LoginCommand {get {return _ loginCommand ?? (_ LoginCommand = new DelegateCommand <string> (s = >{ UserName = new UserModel (). GetUserName (s) ;}, s =>! String. IsNullOrEmpty (s )));}}}}
6. Create View settings binding
Here, we will use MainView as an example to change the layout.
<Page x: Class = "MvvmDemo. mainPage "xmlns =" http://schemas.microsoft.com/winfx/2006/xaml/presentation "xmlns: x =" http://schemas.microsoft.com/winfx/2006/xaml "xmlns: local =" using: MvvmDemo "xmlns: d =" http://schemas.microsoft.com/expression/blend/2008 "xmlns: mc =" http://schemas.openxmlformats.org/markup-compatibility/2006 "mc: ignorable = "d"> <Grid Background = "{ThemeResource ApplicationPageBackgroundThemeBrush}" verticalignment = "Center" HorizontalAlignment = "Center"> <Grid. rowDefinitions> <RowDefinition Height = "50"/> <RowDefinition Height = "50"/> <RowDefinition Height = "50"/> </Grid. rowDefinitions> <Grid. columnDefinitions> <ColumnDefinition Width = "Auto"/> <ColumnDefinition Width = "Auto"/> </Grid. columnDefinitions> <TextBlock Text = "User ID:" Grid. row = "0" Grid. column = "0" Width = "100"/> <TextBlock Text = "username:" Grid. row = "1" Grid. column = "0" Width = "100"/> <TextBox x: Name = "txtUserID" Grid. row = "0" Grid. column = "1" Width = "150" Text = "{x: Bind VM. userId, Mode = OneWay} "/> <TextBlock x: Name =" txbUserName "Grid. row = "1" Grid. column = "1" Width = "150" Text = "{x: Bind VM. userName, Mode = OneWay} "/> <Button x: Name =" btnLogin "Content =" Login "Grid. row = "2" Grid. columnSpan = "2" Width = "150" HorizontalAlignment = "Center" Command = "{x: Bind VM. loginCommand, Mode = OneWay} "CommandParameter =" {Binding Text, ElementName = txtUserID, Mode = OneWay} "/> </Grid> </Page>
Add code in the background
/// <Summary> /// it can be used to itself or navigate to a blank page inside the Frame. /// </Summary> public sealed partial class MainPage: Page {public MainViewModel VM => new MainViewModel (); public MainPage () {this. initializeComponent (); this. dataContext = VM ;}}
7. Create a Model
Using System; using System. collections. generic; using System. linq; using System. text; using System. threading. tasks; namespace MvvmDemo. models {public class UserModel {public string GetUserName (string userid) {return string. format ("succeeded: {0}", userid );}}}
8. Implementation results
The button before entering the content is automatically unavailable:
After entering the content, the button is automatically available:
Click the Login button:
9. Summary
This is a simple login implementation that involves the MVVM View, Viewmodel, and Model. Here, the button is used to automatically determine whether it is available. This judgment is implemented in our Viewmodel. Xbind is involved in the example. This is different from Binding. The details are described in the following section. It can be seen that it is not difficult to implement the Mvvm mode by yourself. However, as the complexity of the project deepens, there will be many problems, such as communication between viewmodes.