Silverlight CommandBinding with Simple MVVM Toolkit

debal_saha-9451
Posted by in Silverlight category on for Intermediate level | Points: 250 | Views : 18310 red flag

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


 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

Page copy protected against web site content infringement by Copyscape

About the Author

debal_saha-9451
Full Name: DEBAL SAHA
Member Level: Starter
Member Status: Member
Member Since: 3/15/2011 4:01:43 AM
Country: India

http://silverlightpractice.blogspot.com/

Login to vote for this post.

Comments or Responses

Posted by: Ashwink2 on: 1/18/2019 | Points: 25
Thanks for your informational Homepage and knowledge. I like to get new ideas with this and also wants to share this entertaining platform http://theyahtzee.com where interested player can play Board game for free and Online.

Login to post response

Comment using Facebook(Author doesn't get notification)