【问题标题】:How to bind a single command to different view models in wpf?如何将单个命令绑定到 wpf 中的不同视图模型?
【发布时间】:2014-12-19 09:26:39
【问题描述】:

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

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

我有一个在两个视图模型中都实现的命令接口。执行方法必须根据数据上下文调用 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
{

}

【问题讨论】:

  • 我不确定我是否理解得很好,但是您可以使用 Button.CommandParameter 将参数传递给命令,如果工作特定于 DataContext,那么您可以编写:

标签: c# wpf mvvm command commandbinding


【解决方案1】:

我认为你很困惑。你说过这两个SearchTreeCommands 根据他们的视图模型有不同的实现,所以他们唯一的共同点是名字,他们实际上并不相关。

您还绑定到视图模型上的属性 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 ;-)
}

【讨论】:

    【解决方案2】:

    PerformSearch添加到IViewModel接口并在Execute()中调用。

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

    这意味着当您的ViewModels 实现接口时,您可以为每个接口提供不同的实现,但ViewModels 之间的接口是通用的,以满足您的 Command 实现的需要。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-04-29
      • 2010-11-28
      • 2014-11-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多