我正在使用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)
,但如预期的那样,结果也是一样的。