Wpf DelegateCommand抛出“;指定的强制转换无效";

Wpf DelegateCommand抛出“;指定的强制转换无效";,wpf,prism,delegatecommand,Wpf,Prism,Delegatecommand,我想使用带有bool作为参数的PRISM delegatecommand。以下是相关代码: public class ChartViewModel : BindableBase { public DelegateCommand<bool?> ChangeZoomPanCommand { get; private set; } private bool isInRealtimeMode; public bool IsInRealtimeMode {

我想使用带有bool作为参数的PRISM delegatecommand。以下是相关代码:

public class ChartViewModel : BindableBase
{
    public DelegateCommand<bool?> ChangeZoomPanCommand { get; private set; }

    private bool isInRealtimeMode;
    public bool IsInRealtimeMode
    {
        get { return isInRealtimeMode; }
        set
        {
            SetProperty(ref isInRealtimeMode, value);
            ChangeZoomPanCommand.RaiseCanExecuteChanged();
        }
    }

    private bool dragToZoom;
    public bool DragToZoom
    {
        get { return dragToZoom; }
        set { SetProperty(ref dragToZoom, value); }
    }


    public ChartViewModel()
    {
        ChangeZoomPanCommand = new DelegateCommand<bool?>(ExecuteChangeZoomPan, CanExecuteChangeZoomPan);
        IsInRealtimeMode = true;
        DragToZoom = true;
    }

    private bool CanExecuteChangeZoomPan(bool? arg)
    {
        return !IsInRealtimeMode;
    }

    private void ExecuteChangeZoomPan(bool? enableZoom)
    {
        if (enableZoom.HasValue)
        {
            DragToZoom = enableZoom.Value;
        }
    }
}
如果我将参数类型更改为string,那么一切似乎都正常。然后我当然会得到一个“False”字符串作为参数,因为这是我的xaml命令参数。为什么这不适用于任何T,因为T似乎没有限制。我已经很难地发现T必须是对象或可为null,但即使是可为null的也似乎不适合。如何处理布尔参数


谢谢

相关的命令参数属性通常被类型化为对象,因此任何文本都被解释为字符串。如果Prism无法自动转换为您的类型,您将必须传入正确的类型,但是在XAML中使用泛型(如
Nullable
)通常是一件痛苦的事情,因此我不建议这样做


要在XAML中转换为简单类型,通常应该能够使用如下绑定:
{binding Source=(sys:Boolean)true}
,其中,
sys
是到
mscorlib
中的
System
命名空间的XMLNS映射。

您可以创建一个
DelegateCommand
而不是
DelegateCommand
,然后像这样处理它:

void ExecuteChangeZoomPan(object obj)
{
    if (obj is bool?)
    {
        bool? arg = obj as bool?;

        // The rest of the code goes here.
    }
}

通过这种方式,
ExecuteChangeZoomPan
可以非常灵活,可以接受像
System.DateTime
一样复杂的类型

我就是这样创建DelegateCommand的新实例的

ICommand ConnectCommand = new DelegateCommand<object>(ConnectExecute,ConnectCanExecute);
ICommand ConnectCommand=new DelegateCommand(ConnectExecute,ConnectCanExecute);
然后如果你想增加零钱

 ((DelegateCommand<object>)ConnectCommand).RaiseCanExecuteChanged();
((DelegateCommand)ConnectCommand).raisecancecutechanged();

我可以接受这一点,目前这是我的解决办法。但为什么会出现上述问题?甚至不调用该命令,只调用
raisecancecutechanged
。这不应该只调用
CanExecuteChangeZoomPan
。使用通用where约束是否有意义?
CanExecute
也会传递命令参数,因此转换也会在那里进行。我认为约束不会改变任何事情。
 ((DelegateCommand<object>)ConnectCommand).RaiseCanExecuteChanged();