【问题标题】:Getting non-UI objects to respond to WPF command bindings让非 UI 对象响应 WPF 命令绑定
【发布时间】:2009-03-03 11:58:57
【问题描述】:

我有一个 ViewModel 类,我想响应按钮触发的内置 Refresh 命令,但我不确定如何声明 CommandTarget。

简单来说,我的代码如下

ViewModel 构造函数以及 CanExecute 和 Executed 事件处理程序 -

    public ViewModel()
    {
        CommandBinding binding = new CommandBinding(NavigationCommands.Refresh, CommandHandler);
        binding.CanExecute += new CanExecuteRoutedEventHandler(binding_CanExecute);
        binding.Executed += new ExecutedRoutedEventHandler(binding_Executed);
        CommandManager.RegisterClassCommandBinding(typeof(ViewModel), binding);
    }
    void binding_Executed(object sender, ExecutedRoutedEventArgs e)
    {
        Debug.Print("Refreshing...");
    }

    void binding_CanExecute(object sender, CanExecuteRoutedEventArgs e)
    {
        e.CanExecute = true;
    }

标记是 -

<Button Command="Refresh">refresh</Button>

现在,我已尝试将此按钮上的 CommandTarget 设置为 {Binding Source={StaticResource ViewModel}},但运行时显示为 Cannot convert the value in attribute 'CommandTarget' to object of type 'System.Windows.IInputElement'

我是命令新手,所以我完全有可能在这里搞错了。任何帮助将不胜感激。

【问题讨论】:

    标签: wpf command


    【解决方案1】:

    RoutedCommands 和 MVVM 不能混用。 RoutedCommands 绑定到可视化树并依赖于 WPF 的 CommandBindings 集合。您应该实现自己的ICommand 类,这些类与 MVVM 模式一起使用。先看看Prism's implementations

    在我自己的 MVVM 项目中,我有几个命令实现:

    • DelegateCommand。调用提供的委托来确定命令是否可以执行,并执行命令。
    • ActiveAwareCommand。与接口 (IActiveAware) 结合使用,并将命令执行发送到当前活动的项目。多个活动感知实现向命令注册自身,命令自动将 CanExecute / Execute 调用路由到当前活动项目。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-19
      • 1970-01-01
      • 1970-01-01
      • 2016-05-07
      • 2015-10-04
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      相关资源
      最近更新 更多