views:

44

answers:

2

How can I have a Command that can be called from both a Window and a UserControl (by hitting a button in either) that uses the same execute and can-execute methods? It seems like if I have the following in my UserControl's XAML, it requires myCommandHandler and canExecuteMyCommand to be in my UserControl class:

<CommandBinding Command="{x:Static local:MyUserControl.MyCommand}"
                Executed="myCommandHandler"
                CanExecute="canExecuteMyCommand"/>

Then if I want to use the same Command in my Window, I again need myCommandHandler and canExecuteMyCommand defined in my Window's class. How can I define a Command such that both my UserControl and Window can access it, but myCommandHandler and canExecuteMyCommand are only defined in one class? Do I need to create my own command class instead of declaring a static RoutedCommand field in MyUserControl?

+1  A: 

In my opinion the best thing you can do is to write your own Command, because, as you said, you can reuse it in different Controls and Windows.

The first approach to create your custom command would be to derive from ICommand. Here is an example of a basic command class:

public abstract class BaseCommand : ICommand
{
    protected IMyViewModel viewModel;

    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    public BaseCommand(IMyViewModel viewModel)
    {
        this.viewModel = viewModel;
    }

    public abstract bool CanExecute(object parameter);
    public abstract void Execute(object parameter);
}

To use the command, for example on a button press the code would look something like this:

<Button Command="{Binding Path=MyReuseableCommand,
                  UpdateSourceTrigger=PropertyChanged}" />

I hope this will help you get the right direction.

mpistrich
A: 

You could try DelegateCommand or RelayCommand then

Avatar