如何将单个命令绑定到wpf中的不同视图模型?

时间:2014-12-19 09:26:40

标签: c# wpf mvvm command commandbinding

我有2个视图及其各自的视图模型。 我在两个视图中都有一个按钮。 单击按钮时,我必须从两个视图中执行相同的命令。

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

我有一个命令界面,它在两个视图模型中实现。 execute方法必须根据数据上下文调用PerformSearch函数,即我在两个具有不同实现的视图模型中都有一个PerformSearch函数。如何从命令的execute方法调用PerformSearch的特定实现?

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
{

}

2 个答案:

答案 0 :(得分:1)

我觉得你很困惑。你已经说过两个SearchTreeCommand根据他们的视图模型有不同的实现,所以他们唯一共享的是名称,它们实际上并不相关。

此外,您绑定到视图模型上的属性 Name ,而不是Type,因此您的SearchTreeCommand类可以是您想要的任何类。

这意味着你可以做一些简单的事情

//View Models
public class SimpleViewModel
{
  public ICommand SearchTreeCommand {get;set;}
}

//View 1 with a DataContext of new SimpleViewModel { SearchTreeCommand = new FirstImplementationOfSearchTreeCommand() }
<Button Command="{Binding SearchTreeCommand}" Content="Next"/>    

//View 2 with a DataContext = new SimpleViewModel { SearchTreeCommand = new SecondImplementationOfSearchTreeCommand() }
 <Button Command="{Binding SearchTreeCommand}" Content="Next"/>

或者如果您需要在视图模型中进行更多区分

//View 1 with a DataContext of new SimpleViewModel { SearchTreeCommand = new FirstImplementationOfSearchTreeCommand() }
<Button Command="{Binding SearchTreeCommand}" Content="Next"/>    

//View 2 with a DataContext = new ComplicatedViewModel { SearchTreeCommand = new SecondImplementationOfSearchTreeCommand() }
 <Button Command="{Binding SearchTreeCommand}" Content="Next"/>

//View Models

///<remarks>Notice I don't implement from anything shared with the SimpleView, no interface</remarks>
public class ComplicatedViewModel
{
  public ICommand SearchTreeCommand {get;set;}

  //I have other stuff too ;-)
}

答案 1 :(得分:0)

PerformSearch添加到IViewModel界面,并在Execute()中将其调用。

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

public interface IViewModel
{
     void PerformSearch();
}

这意味着当您的ViewModels实现界面时,您可以为每个界面提供不同的实现,但是ViewModels之间的界面在您的Command实现的需求中很常见。