Jonathan Birkholz

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 :

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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 :

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

So in the code I can now do:

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

For my WPF visual, I have a DataTemplate :

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

C#, WPF