MVVM Light canExecute 始终为 false,RelayCommand<bool> 而不是 RelayCommand<object>
MVVM Light canExecute always false with RelayCommand<bool> not RelayCommand<object>
有谁知道为什么特定于 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"/>
看the code for 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;
}
您传递给命令的参数是 string "true",而不是 boolean true
, 因此条件将失败,因为 parameter
不是 null
并且 is
子句为假。换句话说,如果参数的值与命令的类型 T
不匹配,则为 returns false
。
如果您真的想将布尔值硬编码到您的 XAML 中(即您的示例不是伪代码),请查看 this question 以了解实现方法。
有谁知道为什么特定于 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"/>
看the code for 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;
}
您传递给命令的参数是 string "true",而不是 boolean true
, 因此条件将失败,因为 parameter
不是 null
并且 is
子句为假。换句话说,如果参数的值与命令的类型 T
不匹配,则为 returns false
。
如果您真的想将布尔值硬编码到您的 XAML 中(即您的示例不是伪代码),请查看 this question 以了解实现方法。