Named Command Decorator

Here is the problem, we have a list of ‘commands’ we wish to show depending on what view model / entity is active. If we just had a collection of ICommands, we could show buttons but what would their content be?

My solution is to use the decorator pattern to decorate commands with a Name that can be used as the content for the buttons.

My decorator looks like :

public class NamedCommand : ICommand{    public NamedCommand(ICommand decoratedCommand, string name)    {        _DecoratedCommand = decoratedCommand;        Name = name;    }

    readonly ICommand _DecoratedCommand;    public string Name { get; set; }

    public void Execute(object parameter)    {        _DecoratedCommand.Execute(parameter);    }

    public bool CanExecute(object parameter)    {        return _DecoratedCommand.CanExecute(parameter);    }

    public event EventHandler CanExecuteChanged;}

I then created an extension method on ICommand :

public static ICommand Name(this ICommand command, string name){    return new NamedCommand(command, name);}

So in the code I can now do:

Commands.Add(new ActionCommand(OnOpen).Name("Open"));

For my WPF visual, I have a DataTemplate :

<DataTemplate DataType="{x:Type Commands:NamedCommand}" >    <Button Content="{Binding Name}"            Command="{Binding }" /></DataTemplate>

This website uses IntenseDebate comments, but they are not currently loaded because either your browser doesn't support JavaScript, or they didn't load fast enough.

Share your opinion! Post your thoughts.