1

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?

Saagar Elias Jacky
  • 2,684
  • 2
  • 14
  • 28
Jim C
  • 4,517
  • 7
  • 29
  • 33

2 Answers2

3

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"
Adil Z
  • 121
  • 3
1

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;}
TDaddy Hobz
  • 454
  • 4
  • 11
  • Thanks for adding that. Since only two UI commands would be affected by this state (bool = "includeExtras"), and both of the handlers in the view model end up calling the same method in the business model (which takes this same parameter), I like having it handled from the start as a call parameter. – Jim C Apr 09 '15 at 19:59