MVVM Pattern With Commanding in Silverlight - 2


In this article I am going to add commanding to the earlier post http://www.c-sharpcorner.com/UploadFile/Mahadesh/8807/.

Lets take a copy of the code created in the previous article . We would be doing some modifications to add the Commanding.

Lets start with the PeopleViewModel.cs

We need to add a new class say UpdatePersonCommand. I would place this class in the PeopleViewModel.cs.

       public class UpdatePersonCommand : ICommand
        {
            public bool CanExecute(object parameter)
            {
                if (parameter != null)
                {
                    CanExecuteChanged.Invoke(parameter, new EventArgs());
                }
                return true;
            }
 
            public event EventHandler CanExecuteChanged; 
            public void Execute(object parameter)
            {
               // We have some work to do here
            } 
        }

Let me also add my command:
 
        public ICommand UpdateVM
        {
            get
            {
                return new UpdatePersonCommand();
            }
        }

Let me now modify the MainPage.xaml.cs. 

I will change the Button_Click handler as shown below:

       private
void Button_Click(object sender, RoutedEventArgs e)
        {
            this.ViewModel.UpdateVM.Execute(this.Resources["ViewModel"] as PeopleViewModel);
        }

What I do is just call the Execute on the Update Command which would modify my ViewModel.
 
As can be seen I pass the PageViewModel Instance in the execute method.
 
Nothing changes in the xaml code.
 
Just call the UpdatePerson in the Execute of the UpdatePersonCommand class.
 
        public void Execute(object parameter)
          {
              (parameter as PeopleViewModel).UpdatePerson();
          }

Run the project. It works the same way.

Thanks. Happy coding.
 

Up Next
    Ebook Download
    View all
    Learn
    View all