【问题标题】:MVVM Light canExecute always false with RelayCommand<bool> not RelayCommand<object>MVVM Light canExecute 总是假的 RelayCommand<bool> 而不是 RelayCommand<object>
【发布时间】:2016-03-21 14:44:13
【问题描述】:

有谁知道为什么特定于 MVVM Light RelayCommand 泛型类型会导致其 canExecute 始终解析为 false 绑定?为了获得正确的行为,我必须使用一个对象,然后将其转换为所需的类型。

注意:canExecute 被简化为布尔值,用于测试不起作用的块,通常是属性 CanRequestEdit。

不起作用:

public ICommand RequestEditCommand {
  get {
    return new RelayCommand<bool>(commandParameter => { RaiseEventEditRequested(this, commandParameter); },
                                  commandParameter => { return true; });
  }
}

作品:

public ICommand RequestEditCommand {
  get {
    return new RelayCommand<object>(commandParameter => { RaiseEventEditRequested(this, Convert.ToBoolean(commandParameter)); },
                                    commandParameter => { return CanRequestEdit; });
  }
}

XAML:

<MenuItem Header="_Edit..." Command="{Binding RequestEditCommand}" CommandParameter="true"/>

【问题讨论】:

  • 我认为 CommandParameter 是一个字符串。
  • 你是对的,CommandParameter 是一个字符串。您认为这会对硬编码为返回 true 的 canExecute 产生什么影响?
  • 奇怪...你可以尝试输入一个函数吗?类似于: RelayCommand x = new RelayCommand(req => { string s = "true"; }, req => canExecute());私有 bool canExecute() { return true }
  • 建议的更改产生了相同的结果。作为旁注,您认为这可能与内联 lambda 有何不同?我知道有时预期的行为会产生不同的结果,所以我只是好奇你的思维过程是什么。

标签: wpf mvvm-light commandbinding commandparameter canexecute


【解决方案1】:

看the code for RelayCommand&lt;T&gt;,具体是我用“!!!”标记的那一行:

public bool CanExecute(object parameter)
{
    if (_canExecute == null)
    {
        return true;
    }

    if (_canExecute.IsStatic || _canExecute.IsAlive)
    {
        if (parameter == null
#if NETFX_CORE
            && typeof(T).GetTypeInfo().IsValueType)
#else
            && typeof(T).IsValueType)
#endif
        {
            return _canExecute.Execute(default(T));
        }

        // !!!
        if (parameter == null || parameter is T)
        {
            return (_canExecute.Execute((T)parameter));
        }
    }

    return false;
}

您传递给命令的参数是 string "true",而不是 boolean true,因此条件将失败,因为 parameter 不是null 和 is 子句为假。换句话说,如果参数的值与命令的类型T 不匹配,则返回false。

如果您真的想将布尔值硬编码到您的 XAML 中(即您的示例不是虚拟代码),请查看 this question 以获取执行此操作的方法。

【讨论】:

  • 感谢您的澄清!仔细观察后,我相信这就是 sexta13 所逃避的,但您提供的详细答案更正确。
猜你喜欢
  • 2011-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-29
  • 2017-01-21
  • 1970-01-01
相关资源
最近更新 更多