To implement the Command binding you have to create a DelegateCommand which implements the ICommand interface. The ICommand interface is available in System.Windows.Input namespace in the System.Windows.dll assembly. It defines the contract for commanding.

- It has an EventHandler “CanExecuteChanged” which occurs when changes occur that affect whether the command should execute.
- It has a method named “CanExecute” and returns boolean value true or false based on whether the command can be executed in its current state.
- Another method named “Execute” which calls when the command is invoked.

Here is the implementation of the ICommand interface:

namespace System.Windows.Input

   public interface ICommand 
   { 
       event EventHandler CanExecuteChanged; 
       bool CanExecute(object parameter); 
       void Execute(object parameter); 
    }
}

Now we have to implement the methods defined in the ICommand interface to our DelegateCommand class. Here is the simple implementation of the same:

using System;
using System.Windows.Input;

namespace Silverlight4.CommandBinding.Demo.CommandBase

    public class DelegateCommand : ICommand
   
        /// <summary> 
        /// Occurs when changes occur that affect whether the command should execute. 
        /// </summary> 
        public event EventHandler CanExecuteChanged;

        Func<object, bool> canExecute; 
        Action<object> executeAction; 
        bool canExecuteCache;

        /// <summary> 
        /// Initializes a new instance of the <see cref="DelegateCommand"/> class. 
        /// </summary> 
        /// <param name="executeAction">The execute action.</param> 
        /// <param name="canExecute">The can execute.</param> 
        public DelegateCommand(Action<object> executeAction, 
                               Func<object, bool> canExecute) 
       
            this.executeAction = executeAction; 
            this.canExecute = canExecute; 
        }

        #region ICommand Members
        /// <summary> 
        /// Defines the method that determines whether the command 
        /// can execute in its current state. 
        /// </summary> 
        /// <param name="parameter"> 
        /// Data used by the command. 
        /// If the command does not require data to be passed, 
        /// this object can be set to null. 
        /// </param> 
        /// <returns> 
        /// true if this command can be executed; otherwise, false. 
        /// </returns> 
        public bool CanExecute(object parameter) 
       
            bool tempCanExecute = canExecute(parameter);

            if (canExecuteCache != tempCanExecute) 
           
                canExecuteCache = tempCanExecute; 
                if (CanExecuteChanged != null) 
               
                    CanExecuteChanged(this, new EventArgs()); 
                
            }

            return canExecuteCache; 
        }

        /// <summary> 
        /// Defines the method to be called when the command is invoked. 
        /// </summary> 
        /// <param name="parameter"> 
        /// Data used by the command. 
        /// If the command does not require data to be passed, 
        /// this object can be set to null. 
        /// </param> 
        public void Execute(object parameter) 
       
            executeAction(parameter); 
       
        #endregion 
    }
}

Implementation of ViewModelBase

Let us now implement the ViewModelBase for our application. Though for this sample application you can directly use the ViewModel, but it is recommended to create a base class implementation by inheriting the INotifyPropertyChanged interface so that, if you are creating multiple ViewModel it will be easier to inherit the base class. Here is the code for that:

using System.ComponentModel;

namespace Silverlight4.CommandBinding.Demo.CommandBase

    public abstract class ViewModelBase : INotifyPropertyChanged 
   
        public event PropertyChangedEventHandler PropertyChanged; 
        /// <summary> 
        /// Called when [property changed]. 
        /// </summary> 
        /// <param name="propertyName">Name of the property.</param> 
        protected void OnPropertyChanged(string propertyName) 
       
            if (PropertyChanged != null) 
           
                PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); 
           
        
    }
}

Implementation of ViewModel

Now our all the base classes are ready to use. Hence, we can go further to create our first ViewModel. In this example we are going to load Customer informations, so we will name it as CustomerViewModel.

First of all we will create a new instance of DelegateCommand “LoadCustomersCommand” which is a ICommand type variable. It takes two parameters. First one is the Action which fires when the command executes and the second one is a Function pointer which returns whether the command can be executed. If it returns true, the command binded to the element will be enabled to do the operation and if it returns false, the command binded to the element will be disabled by default. Once it becomes true by any other operation, the UI thread automatically make the element enabled.

Here in the demo application when the command executes, we will fetch the customer information from the provider and store the data in the ObservableCollection called “CustomerCollection”. We used ObservableCollection because it inherits the INotifyPropertyChanged interface and causes the UI thread to update the UI automatically when the collection changed event occurs binded to the specific UI.

/// <summary>
/// Initializes a new instance of the <see cref="CustomerViewModel"/> class.
/// </summary>
public CustomerViewModel()

    LoadCustomersCommand = new DelegateCommand(LoadCustomers, CanLoadCustomers);
}

/// <summary>
/// Loads the customers.
/// </summary>
/// <param name="parameter">The parameter.</param>
private void LoadCustomers(object parameter)

    CustomerCollection = CustomerProvider.LoadCustomers();
}

/// <summary>
/// Determines whether this instance [can load customers] the specified parameter.
/// </summary>
/// <param name="parameter">The parameter.</param>
/// <returns>
///     <c>true</c> if this instance [can load customers] the specified parameter;
///     otherwise, <c>false</c>.
/// </returns>
private bool CanLoadCustomers(object parameter)

    return true;
}

Implementation of UI (XAML)

As of now, our back end code implmentation is ready and now we have to create our UI to show the customer information. First of all we will create the static instance of the viewmodel as a resource of the UserControl. We named it as “vmCustomer”. Now we will design our UI with a ListBox and a Button. Once we click on the button it should execute the command and load the data in the ListBox.

The ListBox should point it’s ItemSource to the CustomerCollection inside the ViewModel. The button will have the LoadCustomersCommand associated with it. If the canExecute method returns false, you will notice the button as disabled and when it returns true, it will become enabled.

Here is the full XAML implementation:

<UserControl x:Class="Silverlight4.CommandBinding.Demo.MainPage" 
    xmlns=http://schemas.microsoft.com/winfx/2006/xaml/presentation 
    xmlns:x=http://schemas.microsoft.com/winfx/2006/xaml 
    xmlns:d=http://schemas.microsoft.com/expression/blend/2008 
    xmlns:mc=http://schemas.openxmlformats.org/markup-compatibility/2006
   
xmlns:local="clr-namespace:Silverlight4.CommandBinding.Demo.ViewModel" 
    Width="500" Height="300">

    <UserControl.Resources> 
        <local:CustomerViewModel x:Key="vmCustomer"/>
    </UserControl.Resources>

    <Grid x:Name="LayoutRoot" Background="White">
        <Border CornerRadius="10,10,0,0" Background="Black" 
                Height="30" VerticalAlignment="Top" Margin="20,20,20,0">
            <TextBlock Text="Silverlight 4 Command Binding Demo" Foreground="White" 
                       FontWeight="Bold" Margin="5"/> 
        </Border> 
        <ListBox ItemsSource="{Binding CustomerCollection, Source={StaticResource vmCustomer}}" 
                 Margin="20,50,20,40"> 
            <ListBox.ItemTemplate> 
                <DataTemplate> 
                    <Grid> 
                        <Grid.ColumnDefinitions> 
                            <ColumnDefinition Width="150"/> 
                            <ColumnDefinition Width="150"/> 
                            <ColumnDefinition Width="*"/> 
                        </Grid.ColumnDefinitions> 
                        <TextBlock Text="{Binding Path=Name}" Width="100" Grid.Column="0"/> 
                        <TextBlock Text="{Binding Path=Address}" Width="200" Grid.Column="1"/> 
                        <TextBlock Text="{Binding Path=ContactNumber}" Width="100" Grid.Column="2"/> 
                    </Grid> 
                </DataTemplate> 
            </ListBox.ItemTemplate> 
        </ListBox> 
        <Button Command="{Binding LoadCustomersCommand, Source={StaticResource vmCustomer}}" 
                Content="Load Customers" Height="25" Margin="380,267,20,8" /> 
    </Grid>
</UserControl>

Now, you can run the application and press F5 to run it. Try it.

What is so SPECIAL on ASPHostDirectory.com Silverlight Hosting?

We know that finding a cheap, reliable web host is not a simple task so we’ve put all the information you need in one place to help you make your decision. At ASPHostDirectory, we pride ourselves in our commitment to our customers and want to make sure they have all the details they need before making that big decision.

We will work tirelessly to provide a refreshing and friendly level of customer service. We believe in creativity, innovation, and a competitive spirit in all that we do. We are sound, honest company who feels that business is more than just the bottom line. We consider every business opportunity a chance to engage and interact with our customers and our community. Neither our clients nor our employees are a commodity. They are part of our family.

The followings are the top 10 reasons you should trust your online business and hosting needs to us:

- FREE domain for Life - ASPHostDirectory gives you your own free domain name for life with our Professional Hosting Plan and 3 free domains with any of Reseller Hosting Plan! There’s no need to panic about renewing your domain as ASPHostDirectory will automatically do this for you to ensure you never lose the all important identity of your site
- 99,9% Uptime Guarantee - ASPHostDirectory promises it’s customers 99.9% network uptime! We are so concerned about uptime that we set up our own company to monitor people’s uptime for them called ASPHostDirectory Uptime
- 24/7-based Support - We never fall asleep and we run a service that is opening 24/7 a year. Even everyone is on holiday during Easter or Christmast/New Year, we are always behind our desk serving our customers
- Customer Tailored Support - if you compare our hosting plans to others you will see that we are offering a much better deal in every aspect; performance, disk quotas, bandwidth allocation, databases, security, control panel features, e-mail services, real-time stats, and service
- Money Back Guarantee - ASPHostDirectory offers a ‘no questions asked’ money back guarantee with all our plans for any cancellations made within the first 30 days of ordering. Our cancellation policy is very simple - if you cancel your account within 30 days of first signing up we will provide you with a full refund
- Experts in Silverlight Hosting
- Given the scale of our environment, we have recruited and developed some of the best talent in the hosting technology that you are using. Our team is strong because of the experience and talents of the individuals who make up ASPHostDirectory
- Daily Backup Service - We realise that your website is very important to your business and hence, we never ever forget to create a daily backup. Your database and website are backup every night into a permanent remote tape drive to ensure that they are always safe and secure. The backup is always ready and available anytime you need it
- Easy Site Administration - With our powerful control panel, you can always administer most of your site features easily without even needing to contact for our Support Team. Additionally, you can also install more than 100 FREE applications directly via our Control  Panel in 1 minute!

Happy Hosting!