Binding an enum to MVVM Light RelayCommand<T> CommandParameter

3k views Asked by At

I'm trying to bind the command parameter in XAML for a RelayCommand<MessageTokens> as below, where MessageTokens is an enum

 public ICommand OpenInvoiceWindowCommand
        {
            get
            {
                return _openInvoiceWindowCommand ??
                       (_openInvoiceWindowCommand = new RelayCommand<MessageTokens>(OpenInvoiceWindow, prm => CanExecuteOpenInvoiceWindowCommand));
            }
        }

The XAML is:

  <Controls1:RadMenuItem Command="{Binding SupplierInvoiceViewModel.OpenInvoiceWindowCommand}" CommandParameter="{Binding Source={x:Type ShipmentDetails:DebitInvoiceViewModelBase}, Path=MessageTokens.SupplierInvoice}" Header="Register a supplier's invoice"/>

Using Telerik's RadGridView the code crashes with

   at GalaSoft.MvvmLight.Command.RelayCommand`1.CanExecute(Object parameter)
   at Telerik.Windows.Controls.RadMenuItem.CanExecuteApply() in c:\Builds\WPF_Scrum\HotFix_2010_Q3\Sources\Development\Controls\Navigation\Menu\RadMenuItem.cs:line 2105
   at Telerik.Windows.Controls.RadMenuItem.ChangeCommand(ICommand oldCommand, ICommand newCommand) in c:\Builds\WPF_Scrum\HotFix_2010_Q3\Sources\Development\Controls\Navigation\Menu\RadMenuItem.cs:line 2124
   at Telerik.Windows.Controls.RadMenuItem.OnCommandChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) in c:\Builds\WPF_Scrum\HotFix_2010_Q3\Sources\Development\Controls\Navigation\Menu\RadMenuItem.cs:line 1623
   at System.Windows.DependencyObject.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.FrameworkElement.OnPropertyChanged(DependencyPropertyChangedEventArgs e)
   at System.Windows.DependencyObject.NotifyPropertyChange(DependencyPropertyChangedEventArgs args)
   at System.Windows.DependencyObject.UpdateEffectiveValue(EntryIndex entryIndex, DependencyProperty dp, PropertyMetadata metadata, EffectiveValueEntry oldEntry, EffectiveValueEntry& newEntry, Boolean coerceWithDeferredReference, Boolean coerceWithCurrentValue, OperationType operationType)

etc.

If I change the parameter to RelayCommand<string> instead of RelayCommand<MessageTokens> the code runs fine.

I'm loathe to do this since I lose all the benefits of strongly typing my parameters.

I suspect that I am not declaring the enum properly in XAML. I've tried

  CommandParameter = "<fullpath>..MessageTokens.SupplierInvoice>"

but that gives an InvalidCastException in MVVMLight.

Does anyone have any suggestions?

Many thanks Jeremy

Edited with the solution

The issue was because I wasn't properly referring to the inner class in the CommandParameter binding with the + sign.

the correct XAML should be:

<Controls1:RadMenuItem Command="{Binding SalesInvoiceViewModel.OpenInvoiceWindowCommand}" CommandParameter="{x:Static local:DebitInvoiceViewModelBase+MessageTokens.SalesInvoice}" Header="Raise a sales invoice"/>
0

There are 0 answers