Code for the click events in the MVVM with parameters.

While using the MVVM architecture we cannot directly implement the events. To  implement the click and other events we need to implement the ICommand interface. Here we are describing the implementation of the ICommand interface in the real time architecture.


Implementing the ICommand interface to the DelegateCommandBase  abstract class.

public abstract class DelegateCommandBase : ICommand
{
private readonly Func<object, Task> _executeMethod;
private readonly Func<object, bool> _canExecuteMethod;

/// <summary>
/// Creates a new instance of a <see cref=”DelegateCommandBase”/>, specifying both the execute action and the can execute function.
/// </summary>
/// <param name=”executeMethod”>The <see cref=”Action”/> to execute when <see cref=”ICommand.Execute”/> is invoked.</param>
/// <param name=”canExecuteMethod”>The <see cref=”Func{Object,Bool}”/> to invoked when <see cref=”ICommand.CanExecute”/> is invoked.</param>
protected DelegateCommandBase(Action<object> executeMethod, Func<object, bool> canExecuteMethod)
{
if (executeMethod == null || canExecuteMethod == null)
throw new ArgumentNullException(“executeMethod”);

_executeMethod = (arg) => { executeMethod(arg); return Task.Delay(0); };
_canExecuteMethod = canExecuteMethod;
}

/// <summary>
/// Creates a new instance of a <see cref=”DelegateCommandBase”/>, specifying both the Execute action as an awaitable Task and the CanExecute function.
/// </summary>
/// <param name=”executeMethod”>The <see cref=”Func{Object,Task}”/> to execute when <see cref=”ICommand.Execute”/> is invoked.</param>
/// <param name=”canExecuteMethod”>The <see cref=”Func{Object,Bool}”/> to invoked when <see cref=”ICommand.CanExecute”/> is invoked.</param>
protected DelegateCommandBase(Func<object, Task> executeMethod, Func<object, bool> canExecuteMethod)
{
if (executeMethod == null || canExecuteMethod == null)
throw new ArgumentNullException(“executeMethod”);

_executeMethod = executeMethod;
_canExecuteMethod = canExecuteMethod;
}

/// <summary>
/// Raises <see cref=”ICommand.CanExecuteChanged”/> on the UI thread so every
/// command invoker can requery <see cref=”ICommand.CanExecute”/>.
/// </summary>
protected virtual void OnCanExecuteChanged()
{
var handlers = CanExecuteChanged;
if (handlers != null)
{
handlers(this, EventArgs.Empty);
}
}
/// <summary>
/// Raises <see cref=”DelegateCommandBase.CanExecuteChanged”/> on the UI thread so every command invoker
/// can requery to check if the command can execute.
/// <remarks>Note that this will trigger the execution of <see cref=”DelegateCommandBase.CanExecute”/> once for each invoker.</remarks>
/// </summary>
[System.Diagnostics.CodeAnalysis.SuppressMessage(“Microsoft.Design”, “CA1030:UseEventsWhereAppropriate”)]
public void RaiseCanExecuteChanged()
{
OnCanExecuteChanged();
}

async void ICommand.Execute(object parameter)
{
await Execute(parameter);
}

bool ICommand.CanExecute(object parameter)
{
return CanExecute(parameter);
}

/// <summary>
/// Executes the command with the provided parameter by invoking the <see cref=”Action{Object}”/> supplied during construction.
/// </summary>
/// <param name=”parameter”></param>
protected async Task Execute(object parameter)
{
await _executeMethod(parameter);
}

/// <summary>
/// Determines if the command can execute with the provided parameter by invoking the <see cref=”Func{Object,Bool}”/> supplied during construction.
/// </summary>
/// <param name=”parameter”>The parameter to use when determining if this command can execute.</param>
/// <returns>Returns <see langword=”true”/> if the command can execute. <see langword=”False”/> otherwise.</returns>
protected bool CanExecute(object parameter)
{
return _canExecuteMethod == null || _canExecuteMethod(parameter);
}

/// <summary>
/// Occurs when changes happen that affect whether or not the command should execute.
/// </summary>
public event EventHandler CanExecuteChanged;

}


Now will use the DelegateCommandBase  abstract class for developing the DelegateCommand class.

/// <summary>
/// An <see cref=”ICommand”/> whose delegates do not take any parameters for <see cref=”Execute”/> and <see cref=”CanExecute”/>.
/// </summary>
/// <seealso cref=”DelegateCommandBase”/>
/// <seealso cref=”DelegateCommand{T}”/>
public class DelegateCommand : DelegateCommandBase
{
/// <summary>
/// Creates a new instance of <see cref=”DelegateCommand”/> with the <see cref=”Action”/> to invoke on execution.
/// </summary>
/// <param name=”executeMethod”>The <see cref=”Action”/> to invoke when <see cref=”ICommand.Execute”/> is called.</param>
public DelegateCommand(Action executeMethod)
: this(executeMethod, () => true)
{
}

/// <summary>
/// Creates a new instance of <see cref=”DelegateCommand”/> with the <see cref=”Action”/> to invoke on execution
/// and a <see langword=”Func” /> to query for determining if the command can execute.
/// </summary>
/// <param name=”executeMethod”>The <see cref=”Action”/> to invoke when <see cref=”ICommand.Execute”/> is called.</param>
/// <param name=”canExecuteMethod”>The <see cref=”Func{TResult}”/> to invoke when <see cref=”ICommand.CanExecute”/> is called</param>
public DelegateCommand(Action executeMethod, Func<bool> canExecuteMethod)
: base((o) => executeMethod(), (o) => canExecuteMethod())
{
if (executeMethod == null && canExecuteMethod == null)
throw new ArgumentNullException(“executeMethod”, “DelegateCommand delegates cannot be null”);
}

/// <summary>
/// Factory method to create a new instance of <see cref=”DelegateCommand”/> from an awaitable handler method.
/// </summary>
/// <param name=”executeMethod”>Delegate to execute when Execute is called on the command.</param>
/// <returns>Constructed instance of <see cref=”DelegateCommand”/></returns>
public static DelegateCommand FromAsyncHandler(Func<Task> executeMethod)
{
return new DelegateCommand(executeMethod);
}

/// <summary>
/// Factory method to create a new instance of <see cref=”DelegateCommand”/> from an awaitable handler method.
/// </summary>
/// <param name=”executeMethod”>Delegate to execute when Execute is called on the command. This can be null to just hook up a CanExecute delegate.</param>
/// <param name=”canExecuteMethod”>Delegate to execute when CanExecute is called on the command. This can be null.</param>
/// <returns>Constructed instance of <see cref=”DelegateCommand”/></returns>
public static DelegateCommand FromAsyncHandler(Func<Task> executeMethod, Func<bool> canExecuteMethod)
{
return new DelegateCommand(executeMethod, canExecuteMethod);
}

///<summary>
/// Executes the command.
///</summary>
public async Task Execute()
{
await Execute(null);
}

/// <summary>
/// Determines if the command can be executed.
/// </summary>
/// <returns>Returns <see langword=”true”/> if the command can execute,otherwise returns <see langword=”false”/>.</returns>
public bool CanExecute()
{
return CanExecute(null);
}

private DelegateCommand(Func<Task> executeMethod)
: this(executeMethod, () => true)
{
}

private DelegateCommand(Func<Task> executeMethod, Func<bool> canExecuteMethod)
: base((o) => executeMethod(), (o) => canExecuteMethod())
{
if (executeMethod == null && canExecuteMethod == null)
throw new ArgumentNullException(“executeMethod”, “DelegateCommand delegates cannot be null”);
}
}


Now will see the implementation in ViewModel. I am taking DashBoardViewModel  as an example

public class DashBoardViewModel
{

private DelegateCommand<string> _saveClick;

public DelegateCommand<string> SaveClick
{
get { return _saveClick; }
}
public DashBoardViewModel()
{
_saveClick = new DelegateCommand<string>(SaveData);

}

private void SaveData(string value)
{
}
}


Now in the xaml code i will add the button like this

<Button Content=”Save” Margin=”10″ CommandParameter=”{Binding Name}” Command=”{Binding Path=DataContext.SaveClick}” />

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s