Showing Message Dialogs When Using MVVM Pattern In Windows 10 UWP APP

We will learn about ICommands Interface and also see how actually the view knows about its ViewModel and how the view invokes the events on ViewModel which can be done by using ICommands.

Let’s see the steps.

Create new Windows 10 UWP app with MVVM Pattern like the following image:

Create

Create a class called SimpleCommand which implements ICommand interface. This class acts as Enhancement for the ICommand and extracts the code to a separate class.

Icommand interface looks like the following code,

  1. bool CanExecute(object parameter);  
  2. void Execute(object parameter);  
  3. event EventHandler CanExecuteChanged;  
The Execute method is only invoked when CanExecute returns true. If CanExecute method returns false then the binding control is disabled. To know the CanExecute value, listen to the CanExecuteChanged event, that may vary based on the parameter passed.

Now Create ViewModel class called ViewModelBase and write one method to show the message dialog; it looks like the following code.
  1. public class ViewModelBase   
  2. {  
  3.     public SimpleCommand SimpleCommand   
  4.   {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public ViewModelBase()  
  9.     {  
  10.         this.SimpleCommand = new SimpleCommand(this);  
  11.     }  
  12.     public async void show()  
  13.     {  
  14.         var dialog = new MessageDialog("Learn to build windows 10 UWP app!");  
  15.         await dialog.ShowAsync();  
  16.     }  
  17. }  
SimpleCommand Class look like the following screen.
  1. public class SimpleCommand: ICommand   
  2. {  
  3.     public ViewModelBase Viemodel   
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8.     public SimpleCommand(ViewModelBase viewmodel)   
  9.     {  
  10.         this.Viemodel = viewmodel;  
  11.     }  
  12.     public event EventHandler CanExecuteChanged;  
  13.     public bool CanExecute(object parameter)   
  14.     {  
  15.         return true;  
  16.   
  17.     }  
  18.   
  19.     public void Execute(object parameter)   
  20.     {  
  21.         this.Viemodel.show();  
  22.     }  
  23. }  
In Execute method call the viewmodel method as you want. Now go to your view MainPage.XAML page and set your viewmodel to this page like the following code, Add the xaml namespace to access the viewmodel folder.
  1. xmlns:vm="using:MVVMButton.ViewModel"  
  2.   
  3. <Page.Resources>  
  4. <vm:ViewModelBase x:Key="viewModel"></vm:ViewModelBase>  
  5. </Page.Resources>  
I am going to bind the command to button to show the message dialog.
  1. <Button Content="Click" HorizontalAlignment="Center" Command="{Binding Path=SimpleCommand,Source={StaticResource viewModel}}"></Button> 
Now run the application and check the output looks like the following image

output
For more information on Windows 10 UWP, refer to my e-book,

 


Similar Articles