How to pass a Nullable <Boolean> value to CommandParameter?

I am using the MVVM Light library. From this library, I use RelayCommand<T> to define commands with an argument of type T

Now I have defined a RelayCommand , which requires an argument of type Nullable<bool> :

  private RelayCommand<bool?> _cmdSomeCommand; public RelayCommand<bool?> CmdSomeCommand { get { if (_cmdSomeCommand == null) { _cmdSomeCommand = new RelayCommand<bool?>(new Action<bool?>((val) => { /* do work */ })); } return _cmdSomeCommand; } } 

How can I assign a CommandParameter from my XAML code?

I tried passing a boolean, but this throws the following exception:

System.InvalidCastException . Invalid listing from 'System.Boolean' to 'System.Nullable`1 [[System.Boolean, mscorlib, Version = 4.0.0.0, Culture = neutral, PublicKeyToken = b77a5c561934e089]].

I also tried to define static properties containing bool? values โ€‹โ€‹and refer to them from XAML:

 public static class BooleanHelper { public static bool True { get { return true; } } public static bool False { get { return false; } } public static bool? NullableTrue { get { return true; } } public static bool? NullableFalse { get { return false; } } } 

XAML:

 <Button Command="{Binding CmdSomeCommand}" CommandParameter="{x:Static my:BooleanHelper.NullableTrue}" /> 

But this raises the same exception. I also tried returning new Nullable<bool>(true) , but as expected, this has the same result.

+6
source share
1 answer

It seems that MVVM Light is faulty for handling the parameter differently between Execute and CanExecute and does not handle the null value appropriately.

See the code https://github.com/paulcbetts/mvvmlight/blob/master/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(NET35)/Command/RelayCommandGeneric.cs#L198 Lines 198-205

What happens, this leads to your exception and can be easily reproduced using the following code:

 object t1 = (bool?)true; // issue: for Nullable<T>, GetType will return T if (t1.GetType() != typeof(bool?)) { if (t1 is IConvertible) { var val = Convert.ChangeType(t1, typeof(bool?), null); } } 

I suspect that you can only submit an error report, because you can perfectly pass a parameter with the option nullable as a parameter, it is being processed with errors.

+2
source

Source: https://habr.com/ru/post/1013419/


All Articles