SIGN UP MEMBER LOGIN:    
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
share this article :
post comment
 
Nevron Gauge for SharePoint
Become a Sponsor
PREMIUM SPONSORS
  • ceTE software specializes in components for dynamic PDF generation and manipulation. The DynamicPDF™ product line allows you to dynamically generate PDF documents, merge PDF documents and new content to existing PDF documents from within your applications.
    The leading .NET charting control now features PDF, Flash and Silverlight export, visualization of large datasets and more. Deliver true charting functionality to your BI, Scorecard, Presentation or Scientific apps. Download evaluation now.
Become a Sponsor