简体   繁体   English

RelayCommand <bool> 抛出无效的强制转换异常

[英]RelayCommand<bool> throws invalid cast exception

I'm trying to parameterize a RelayCommand but am getting a runtime cast exception. 我正在尝试参数化RelayCommand,但遇到运行时强制转换异常。

Here are the relevant xaml and view model lines: 这是相关的xaml和视图模型行:

XAML XAML

<MenuItem Header="Save Project As" Command="{Binding Main.SaveProjectAsRelayCommand}" CommandParameter="false" />

ViewModel 视图模型

public RelayCommand<bool> SaveProjectAsRelayCommand { get; set; }

SaveProjectAsRelayCommand = new RelayCommand<bool>(SaveProjectAs, ProjectTaskCanExecute);

private void SaveProjectAs(bool b){...}
private bool ProjectTaskCanExecute(bool b){...}

When I click the File Menu, GalaSoft throws an 当我单击文件菜单时,GalaSoft会抛出一个

InvalidCastException ("Specified cast is not valid) InvalidCastException(“指定的类型转换无效)

When I remove the parameter from everything, works fine. 当我从所有内容中删除参数时,效果很好。

Do I have to do something to enable "false" to be cast to a bool? 我是否需要做一些事情以使“ false”被强制转换为布尔值?

The Type Converter must be converting it to a string instead of a bool. 类型转换器必须将其转换为字符串而不是布尔值。

<MenuItem Header="Save Project As" Command="{Binding Main.SaveProjectAsRelayCommand}" >
 <MenuItem.CommandParameter>
      <x:Boolean>False<x:Boolean>
 </MenuItem.CommandParameter>
</MenuItem>

Try the above. 尝试以上。 You will have to use the following name space in the XAML. 您将必须在XAML中使用以下名称空间。

xmlns:x="clr-namespace:System;assembly=mscorlib"

Alternatively, you could create a property in your 'main' that you bind to 或者,您可以在绑定到的“主”中创建一个属性

<MenuItem Header="Save Project As" Command="{Binding Main.SaveProjectAsRelayCommand}" CommandParameter="{Binding Main.IsTask}" />

In the main VM you will than have 在主虚拟机中,您将拥有

public bool IsTask{get;set;}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM