Tuesday, February 21, 2012

Commanding in Silverlight MVVM

Create class named DelegateCommand contains command arguments and Executed Method.

 public delegate void DelegateCommandExecutedEventHandler(Object sender, 
                             DelegateCommandExecutedEventArgs e);

    public class DelegateCommandExecutedEventArgs : EventArgs
    {
        public DelegateCommand Command { get; set; }
        public Object Parameter { get; set; }

        public DelegateCommandExecutedEventArgs(DelegateCommand command, Object parameter)
        {
            Command = command;
            Parameter = parameter;
        }
    }

    public class DelegateCommand : ICommand
    {

        private Boolean _canExecuteCore;
        public Boolean CanExecuteCore
        {
            get { return _canExecuteCore; }
            set { _canExecuteCore = value; OnCanExecuteChanged(); }
        }

        public event EventHandler CanExecuteChanged;

        protected void OnCanExecuteChanged()
        {
            EventHandler temp = CanExecuteChanged;
            if (temp != null)
            {
                temp(this, EventArgs.Empty);
            }
        }

        public event DelegateCommandExecutedEventHandler Executed;

        protected void OnExecuted(DelegateCommand command, Object parameter)
        {
            DelegateCommandExecutedEventHandler temp = Executed;
            if (temp != null)
            {
                temp(this, new DelegateCommandExecutedEventArgs(command, parameter));
            }
        }

        public DelegateCommand()
        {
            CanExecuteCore = true;
        }

        public Boolean CanExecute(object parameter)
        {
            return CanExecuteCore;
        }

        public void Execute(object parameter)
        {
            OnExecuted(this, parameter);
        }
    }

Now using Command in XAML page

 <Button Content="Save"
         Command="{Binding SaveCommand}"
         CommandParameter="SaveEmployee"
         Margin="20,0,0,0"
         Height="30"
         Grid.Row="1"
         Grid.Column="1" />


Execute Command From ViewModel 

public class EmployeeViewModel
{ 
    public DelegateCommand SaveCommand { get; set; } 
 
    public EmployeeViewModel()
    {
        SaveCommand = new DelegateCommand();
        SaveCommand.Executed += new DelegateCommandExecutedEventHandler(SaveCommand_Executed); 
    } 
    void SaveCommand_Executed(object sender, DelegateCommandExecutedEventArgs e)
    {
            if (e.Parameter == null || string.IsNullOrEmpty(e.Parameter.ToString()))
                return;
 
           //......here your code 
    }
}

No comments:

Post a Comment