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

Datetime:2016-08-23 01:24:24          Topic: MVVM Model           Share

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 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,

bool CanExecute(object parameter);  
void Execute(object parameter);  
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.

public class ViewModelBase   
{  
    public SimpleCommand SimpleCommand   
  {  
        get;  
        set;  
    }  
    public ViewModelBase()  
    {  
        this.SimpleCommand = new SimpleCommand(this);  
    }  
    public async void show()  
    {  
        var dialog = new MessageDialog("Learn to build windows 10 UWP app!");  
        await dialog.ShowAsync();  
    }  
}  

SimpleCommand Class look like the following screen.

public class SimpleCommand: ICommand   
{  
    public ViewModelBase Viemodel   
    {  
        get;  
        set;  
    }  
    public SimpleCommand(ViewModelBase viewmodel)   
    {  
        this.Viemodel = viewmodel;  
    }  
    public event EventHandler CanExecuteChanged;  
    public bool CanExecute(object parameter)   
    {  
        return true;  
  
    }  
  
    public void Execute(object parameter)   
    {  
        this.Viemodel.show();  
    }  
}  

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.

xmlns:vm="using:MVVMButton.ViewModel"  
  
<Page.Resources>  
<vm:ViewModelBase x:Key="viewModel"></vm:ViewModelBase>  
</Page.Resources>  

I am going to bind the command to button to show the message dialog.

<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

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





About List