What you want to see on DotNetFunda.com ?
Go to DotNetFunda.com
Twitter TwitterLinkedIn
YouTubeGoogle
 Online : 5012 |  Welcome, Guest!   Register  Login
Home > Articles > Silverlight > Silverlight CommandBinding with Simple MVVM Toolkit

Silverlight CommandBinding with Simple MVVM Toolkit

Article posted by Debal_saha@yahoo.com on 11/21/2011 | Views: 6621 | Category: Silverlight | Level: Intermediate | Points: 250 red flag


In this article, we shall learn about Silverlight CommandBinding with Simple MVVM Toolkit.

Download


 Download source code for Silverlight CommandBinding with Simple MVVM Toolkit


Last Week I was studying on CommandBinding in Silverlight. I came to know that only Silverlight 4 supports CommandBinding. Through a short description I want to demonstrate how easy it is to do commandBinding in Silverlight using MVVM toolkit. Yes, we have to download Silverlight MVVM toolkit for develop this application. But before that, lets browse through the brief history of CommandBinding.

Silverlight 4 enables CommandBinding by using properties like Command and CommandParameter only for Button Base Class which means that CommandBinding can only support those elements in Silverlight which are derived from Button Base Class and will be executing only by Click event.  For e.g., button, Hyperlink Button, Repeat Button, menu controls etc. (N.B. In the previous version of Silverlight 4 CommandBinding was not possible).

Using CommandBinding in application for controls we need to use the contract ICommand from the namespace System.Windows.Input . Command work with two properties Command and CommandParameter . Here is short description of Command and CommandParameter property in below:

Command: This property gets or sets the command to invoke when this button is pressed. This takes ICommand interface as a type.

Commandparameter :  This property gets or sets the parameter to pass to the Command Property. The default is null. This property takes Object as a Type.

See I give a snapshot of Button Base Class, so it will be better to understand how they have defined in this Class.

public abstract class ButtonBase : ContentControl

{

public static readonly DependencyProperty ClickModeProperty;

public static readonly DependencyProperty CommandParameterProperty;

public static readonly DependencyProperty CommandProperty;

.

.

.

// Summary:

// Initializes a new instance of the System.Windows.Controls.Primitives.ButtonBase

// class.

protected ButtonBase();

public ClickMode ClickMode { get; set; }

// Summary:

// Gets or sets the command to invoke when this button is pressed.

//

// Returns:

// The command to invoke when this button is pressed. The default is null.

public ICommand Command { get; set; }

//

// Summary:

// Gets or sets the parameter to pass to the System.Windows.Controls.Primitives.ButtonBase.Command

// property.

//

// Returns:

// The parameter to pass to the System.Windows.Controls.Primitives.ButtonBase.Command

// property. The default is null.

public object CommandParameter { get; set; }

.

.

.

}

So, here you can see the two Properties have been defined in Button Base Class and for that result we can implement CommandBinding in all derived class of Button base.

Now it is time to create a Project in Silverlight and use CommandBinding. Ok, but before that there would be a question which might rise in beginner ‘s mind that when we can easily handle a button event using click event in Xaml page or code behind , so why we need to go to use ICommand or CommandBinding?

Fine, I would like to mention that today most of Silverlight Projects are going in MVVM architecture. If you are very new in Silverlight, remember one thing is that MVVM (Model - View - View Model) is architecture of your application that separates the application into distinct layers.Suppose you are doing in a project based on MVVM, and you want to show a button click event that will load some information in your UI Page. In my Model,  I use to store information of data that will be displayed in UI page and In View Model,  I place logic to get/ fetch data from model this means when user click on the button , the response will go to View - Model from View and then in Model to fetch data.

So, by using CommandBinding, it is very straightforward. Just you need to bind the Command in your view page and this will trigger in your View Model and modify the data in Model.This is first point to using CommandBinding and another is that we need not to write tedious event handing code in our code behind page.

Ok, let’s do it. I had mentioned above to use MVVM toolkit for CommandBinding in this application. So, we need to download this toolkit. Let’s create a project in Silverlight step by step. Yeah, my project is built on Silverlight 5 version. So, first be sure that you have properly installed Silverlight 5 sdk and other necessary items for developing Silverlight 5 application. For further information please read about Silverlight 5 here.

1. Open Visual Studio 2010 and click Tools tab and select Extension Manager. Follow the Image below. On the Search text box write Simple MVVM, make sure that from the right side template you have Select Online Gallery and your PC is connected with internet.

Pic -1

2. After Download this and successfully Installed in your machine, (Close the Visual Studio and open it again) create a new Project and name it SimpleMVVM CommandBinding. See the Pic -2

Pic- 2

3. Now you can see that your Project is ready with some additional folder in the name of Models, Locators, services, View and View-Model etc. See in Pic -3 to get a better understand.

Pic-3

4. To do CommandBinding in your Silverlight application you need to do create a DelegateCommand Class. In this Class you need to implement ICommand interface. By default in Silverlight 4 beta doesn’t have any implementation of ICommand interface. We need to do all these by own hand. Here is little description about ICommand interface. 

ICommand interface is the core CommandBinding in Silverlight. Let’s see what are the member in ICommand Interface .  See your code will look like this:

    public class DelegateCommand : ICommand
    {
 
      public bool CanExecute(object parameter)
        {
            throw new NotImplementedException();
        }
 
     public event EventHandler CanExecuteChanged;






            public void Execute(object parameter)         {             throw new NotImplementedException();         }     }



When you try to implement the members of ICommand interface , you can see below members are included in it.

  • CanExecute :  This method has a return type bool, it will be true if the command execute else it returns false. 
  • Execute: The method executes when the command is triggered i.e. the method calls when the Command invoked.
  • CanExecuteChanged: This is an event handler which is raised when any changes are going on the Command executing time.

So, these are the members of ICommand interface. However, Silverlight doesn’t provide any special Command Class to implement ICommand interface, but you have freedom to create a dozens of different Command classes, but this is best choice to make a general Command class that can be reused for different tasks.

I know after discussing up to now, any one may feel bore to do this task . For one simple button click event handling needs to do lots of work !!!!. First create a DelegateCommand class , Second  implement ICommand interface (using System.Windows.Input namespace), third write your code in DelegateCommand Class . Then Come to ViewModel create a Property with type of Icommand . In ViewModel Constructor create instance of Delegatecommmand class pass parameter in it and assign it with newly create property. Lastly bind the Command property within your xaml Page in Button etc etc etc....

Now , I can get rid of all that . Yes, I have MVVM toolkit . Using this toolkit it is very easy to do CommandBinding in your Silverlight application. For more information about Simple MVVM toolkit just go to Tony’s blog here. where he described how easy now work with MVVM in Silverlight.

I’m now going to develop my application.  In above step 1 and 2 , I showed you how we can achieve through the toolkit.

One thing I want to mention that When you open properly our solution using MVVM toolkit . You can see in Xaml page that trigger is using  just like below . I delete this because I need to do work with Command Binding not with Action/Trigger.  So , this is below code which I delete:

<!-- Add reference to Microsoft.Expression.Interactions.dll, System.Windows.Interactivity.dll -->

<!-- Use mvvmxmlns snippet to add i and ei namespace prefixes -->

<i:Interaction.Triggers>

<i:EventTrigger EventName="SelectionChanged">

<ei:CallMethodAction

TargetObject="{Binding}"

MethodName="ShowCustomer"/>

</i:EventTrigger>

</i:Interaction.Triggers>

 

Go to ViewModel folder in solution explorer and open the CustomerViewModel.cs file. You just need to create a property in property region. It is just two steps of work. First use the simple MVVM toolkit snippets "mvvmcommandcanex" and press two times tab, see your code is ready, and now need to do simple modification. Look at the code that I have done:

#region Properties

/// <summary>

/// I have Create a property using mvvmcommandcanex snippest

/// </summary>

private DelegateCommand<object> myMethodCommand;

public DelegateCommand<object> BindCommand

{

get

{

if (myMethodCommand == null)

myMethodCommand = new DelegateCommand<object>(NewCustomer, CanExecute);

return myMethodCommand;

}

}

#endregion

 

5.Yes , you may be pondering that what is NewCustomer and CanExecute within the delegatecommand constructor . Fine, these are the two methods I have to define in Viewmodel and delegate command class is expecting one or two arguments in its constructor. See how the DelegateCommand Class has been defined in Simple MVVM. look the below code:

public class DelegateCommand<T> : ICommand

{

public DelegateCommand(Action<T> executeAction);

public DelegateCommand(Action<T> executeAction, Func<T, bool> canExecute);

public event EventHandler CanExecuteChanged;

public bool CanExecute(object parameter);

public void Execute(object parameter);

public void RaiseCanExecuteChanged();

}

6. See the code  what the constructor is taking as a argument . One thing also is to be noted that we can also pass one argument in DelegateCommand constructor.

7. Now we move to our Xaml page and directly bind this property within button. See below:

<Button Content="New Customer" Grid.Row="5" Grid.ColumnSpan="2" Height="30" Width="100"

Background="Pink" CommandParameter="param"

Command="{Binding Path=BindCommand}"/>

 

8. You have finished your task. Just build your application and run it .

9. In the application I have a button and some text boxes. When we click on button some dummy data show in textboxes.

The below pic -4 shows the result.

Pic -4

Hope, this has given a basic idea using MVVM toolkit .  If you like this article Please vote and give me your feedback.

Thanks

If you like this article, subscribe to our RSS Feed. You can also subscribe via email to our Interview Questions, Codes and Forums section.

Page copy protected against web site content infringement by Copyscape
Found interesting? Add this to:



Please Sign In to vote for this post.

About DEBAL SAHA

Experience:1 year(s)
Home page:http://silverlightpractice.blogspot.com/
Member since:Tuesday, March 15, 2011
Level:Starter
Status: [Member]
Biography:
>> Write Response - Respond to this post and get points
Related Posts

In most of my career, I worked with these kinds of Systems. How track someone? How to intercept Phone calls, How to Spy on Someone? How to Sniff on Devices? The things you see on TV, some of them are not true and some are true and possible. Before you even try to do something illegal on the internet, you must know that there are people who might be looking at you with basic intelligence systems like the one I mentioned or the one I will present to you now. As you know you can just get the IP address of your client with just one line of code in c# and in this article I will show you how to use it to get their location and possibly more.

In this article, I will guide you to understand the functionality of Silverlight 4 PathListBox Control. Also, I will guide you step-by-step to create your first PathListBox control demo application. Here we will create the above two samples where the collection of texts will position them in proper location on the edge of the circular path.

This Article will help to understand how the initial data required by Silverlight Application will be transfer to it from ASP.NET Page. This helps in transferring dynamic settings from ASP.NET Page to Silverlight application

You might want to show notification from your application like outlook does. As a Silverlight Evangelist I will only demonstrate the Silverlight way. It is just an easy thing to do.

In this article, I shall try to explain how to work with multiple .xaml file in a single Silverlight application.

More ...
About Us | Contact Us | The Team | Advertise | Software Development | Write for us | Testimonials | Privacy Policy | Terms of Use | Link Exchange | Members | Go Top
General Notice: If you find plagiarised (copied) contents on this page, please let us know the original source along with your correct email id (to communicate) for further action.
Copyright © DotNetFunda.Com. All Rights Reserved. Copying or mimicking the site design and layout is prohibited. Logos, company names used here if any are only for reference purposes and they may be respective owner's right or trademarks. | 5/21/2013 2:47:30 PM