如何将Nullable <Boolean>值传递给CommandParameter?

Chr*_*ris 6 c# xaml nullable icommand

我正在使用MVVM Light库.从这个库我RelayCommand<T>用来定义带有类型参数的命令T.

现在我已经定义了一个RelayCommand需要类型的参数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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

如何从我的XAML代码中分配CommandParameter?

我试图传递一个布尔值,但这会导致以下异常:

System.InvalidCastException:从'System.Boolean'到'System.Nullable`1 [[System.Boolean,mscorlib,Version = 4.0.0.0,Culture = neutral,PublicKeyToken = b77a5c561934e089]]'的无效演员表.

我还尝试定义包含bool的静态属性?值并从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; } }
}
Run Code Online (Sandbox Code Playgroud)

XAML:

<Button Command="{Binding CmdSomeCommand}" CommandParameter="{x:Static my:BooleanHelper.NullableTrue}" />
Run Code Online (Sandbox Code Playgroud)

但这会导致抛出相同的异常.我也试图回归new Nullable<bool>(true),但正如预期的那样,这也有同样的结果.

gre*_*k40 2

看起来 MVVM Light 因以不同的方式处理参数ExecuteCanExecute未以正确的方式处理可为空而出错。

请参阅代码https://github.com/paulcbetts/mvvmlight/blob/master/GalaSoft.MvvmLight/GalaSoft.MvvmLight%20(NET35)/Command/RelayCommandGeneric.cs#L198第 198-205行

那里发生的事情会导致异常,并且可以使用以下代码轻松重现:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)

我怀疑你只能提交一个错误报告,因为你可以完美地传递可为空的参数,它被处理为错误