ARTICLE

MVVM Pattern With Commanding in Silverlight - 2

Posted by Mahadesh Mahalingappa Articles | Silverlight with C# August 14, 2011
In this article yo uwill learn how to work with Commanding in Silverlightg.
Reader Level:
Download Files:
 

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.
 

Login to add your contents and source code to this article
post comment
     
COMMENT USING
PREMIUM SPONSORS
DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and add new content to existing PDF documents from within your applications.
Join a Chapter
SPONSORED BY
  • PDF reports have never been easier to create. With our included WYSIWYG Designer, you can layout your reports, set up your data source and let DynamicPDF ReportWriter do the rest.
Join a Chapter