2016-03-21 85 views
3

有谁知道为什么使用MVVM Light RelayCommand通用类型会导致其canExecute始终解析为绑定错误?为了获得正确的行为,我必须使用一个对象,然后将其转换为所需的类型。MVVM Light canExecute始终为false,并且RelayCommand <bool> not RelayCommand <object>

注意: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

+0

你是正确的,CommandParameter是作为一个字符串。你如何认为这会对canExecute产生影响,而硬编码会返回true? – Rock

+0

奇怪......你可以尝试放入一个函数吗?例如: RelayCommand x = new RelayCommand (req => {string s =“true”;},req => canExecute()); private bool canExecute() { return true } – sexta13

回答

2

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

要传递到您的命令的参数是字符串“真”,而不是布尔true,所以病情会失败因为parameter不是nullis子句是错误的。换句话说,如果参数的值与该命令的类型T不匹配,则它返回false

如果您确实想要将布尔值硬编码到您的XAML中(即您的示例不是虚拟代码),请参阅this question以了解如何执行此操作。

+0

谢谢你清理那个!经过仔细观察,我相信这是sexta13所避免的,但您提供的详细答案更正确。 – Rock

相关问题