DelegateCommand Extensions

If I remember well, I took the base from Microsoft .toolkit. After using it hundred of times I added a pair of extensions to reduce the code lines, the Extensions code:


public static class Commands
{
public static DelegateCommand Create(Action action)
{
return new DelegateCommand()
{
ExecuteCommand = action
};
}
public static DelegateCommand<T> Create<T>(Action<T> action)
{
return new DelegateCommand<T>()
{
ExecuteCommand = action
};
}
}

The base code:


public class DelegateCommand : ICommand     {
public Action ExecuteCommand { get; set; }
public Func<object, bool> CanExecuteCommand { get; set; }

public bool CanExecute(object parameter)
{
if (CanExecuteCommand != null)
return CanExecuteCommand(parameter);
return true;
}

public void Execute(object p)
{
if (ExecuteCommand != null)
ExecuteCommand();
}

public event EventHandler CanExecuteChanged;
}

public class DelegateCommand<T> : ICommand     {
public Action<T> ExecuteCommand { get; set; }
public Func<T, bool> CanExecuteCommand { get; set; }

public bool CanExecute(object parameter)
{
if (CanExecuteCommand != null)
return CanExecuteCommand((T)parameter);
return true;
}

public void Execute(object parameter)
{
if (ExecuteCommand != null)
ExecuteCommand((T)parameter);
}

public event EventHandler CanExecuteChanged;
}

[/sourcecode ]

And then, the use reducing lines:



SuperCommand = Commands.Create(() =>
{
...
});

That’s all reducing lines.

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