MVVM Light中,使用RelayCommand<bool>时canExecute总是为false,而非RelayCommand<object>。

3

有人知道为什么在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"/>

1
我认为CommandParameter是以字符串形式传递的。 - sexta13
你是正确的,CommandParameter 作为字符串传递。你认为这会对硬编码返回 true 的 canExecute 产生什么影响? - Rock
奇怪...你能试着把它放在一个函数里吗?像这样: RelayCommand<bool> x = new RelayCommand<bool>(req => { string s = "true"; }, req => canExecute()); private bool canExecute() { return true; } - sexta13
建议的更改产生了相同的结果。顺便说一句,你怎么想到这可能不同于内联lambda?我知道有时期望的行为会产生不同的结果,所以我只是好奇你的思考过程是什么。 - Rock
1个回答

2

请查看RelayCommand<T>的代码,特别是我标记为“!!!”的那一行:

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;
}

您传递给命令的参数是字符串"true",而不是布尔值true,因此条件将失败,因为parameter不是nullis子句为false。换句话说,如果参数的值与命令的类型T不匹配,则返回false
如果您确实想在XAML中硬编码布尔值(即您的示例不是虚拟代码),则可以查看此问题以了解如何这样做。

您IP地址为143.198.54.68,由于运营成本限制,当前对于免费用户的使用频率限制为每个IP每72小时10次对话,如需解除限制,请点击左下角设置图标按钮(手机用户先点击左上角菜单按钮)。 - Rock

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接