Jim C
Jim C

Reputation: 4648

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?

Upvotes: 1

Views: 1193

Answers (2)

TDaddy Hobz
TDaddy Hobz

Reputation: 464

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

Upvotes: 1

Adil Z
Adil Z

Reputation: 121

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"

Upvotes: 3

Related Questions