Search code examples
c#wpfmvvmcommandcommandbinding

How to bind a single command to different view models in wpf?


I have 2 views and their respective view models. I have a button in both the views. On click of a button I have to execute the same command from both the views.

<Button Command="{Binding SearchTreeCommand}" Content="Next"/>

I have a command interface which is implemented in both the view models. The execute method has to call a PerformSearch function depending on the data context i.e I have a PerformSearch function in both the viewmodels with different implementation. How do I call the particular implementation of PerformSearch from the execute method of the command?

public class SearchTreeCommand : ICommand
{
    private readonly IViewModel m_viewModel;

    public SearchTreeCommand(IViewModel vm)
    {
        m_viewModel = vm;
    }

    event EventHandler ICommand.CanExecuteChanged
    {
        add { }
        remove { }
    }

    public void Execute(object param)
    {
        //how do I call the PerformSearch method here??
    }

    public bool CanExecute(object param)
    {
        return true;
    }
}

public interface IViewModel
{

}

Solution

  • Add PerformSearch to the IViewModel interface and call it in Execute().

    public void Execute(object param)
    {
        m_viewModel.PerformSearch();
    }
    
    public interface IViewModel
    {
         void PerformSearch();
    }
    

    This means that when your ViewModels implements the interface you can provide different implementations to each but the interface is common between the ViewModels for your Command implementation's needs.