简体   繁体   中英

RelayCommand<bool> throws invalid cast exception

I'm trying to parameterize a RelayCommand but am getting a runtime cast exception.

Here are the relevant xaml and view model lines:

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

InvalidCastException ("Specified cast is not valid)

When I remove the parameter from everything, works fine.

Do I have to do something to enable "false" to be cast to a bool?

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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