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

6

我正在使用MVVM Light库。 我使用RelayCommand<T>从该库中定义带有类型T参数的命令。

现在我已经定义了一个需要类型为Nullable<bool>参数的RelayCommand

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

如何在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; } }
}

XAML:

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

但这会导致相同的异常被抛出。我还尝试返回 new Nullable<bool>(true),但如预期的那样,结果也是一样的。

你看过这个吗?https://dev59.com/ZU3Sa4cB1Zd3GeqPydf1 - tolanj
虽然这并不是问题的解决方案,但可以将参数定义为“object”,并在操作体中进行手动转换。 - wondra
1个回答

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

我猜你只能提交一个错误报告,因为你可以完美地将可空参数作为参数传递,但它会处理错误


谢谢!这确实引起了问题。我已经提交了一个错误报告:链接 - Chris
四个月后,我也遇到了同样的问题。看起来它不会被修复 :( - Speuline
@Speuline 我不太确定我在问题中引用的代码是否反映了当前的MVVM Light实现。但是,如果你能获取到当前的源代码并且问题确实存在于其中,你可以自己修复这个问题并感到高兴。 - grek40

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接