在 Prism / Xamarin Forms 中使用通用委托命令时的奇怪行为

Odd Behavior When Using Generic Delegate Command In Prism / Xamarin Forms

我正在尝试使用 Prism 组件中的 DelegateCommand<T> 类型。

假设我的视图模型中有以下内容:

public DelegateCommand<int> TestCommand
{
    get;

    set;
}

public void TestCommandExecute(int parameter)
{
    return;
}

在视图模型的构造函数中,我使用以下内容初始化 TestCommand 属性:

TestCommand = new DelegateCommand<int>(TestCommandExecute);

如果我这样做,应用程序似乎 崩溃 并显示 空白 屏幕。我还观察到在这种情况下从未调用 OnNavigatedTo 方法。

我观察到,如果我将 TestCommand 的类型从 DelegateCommand<int> 更改为 DelegateCommand(然后相应地调整 TestCommandExecute 方法的签名,应用程序不会 崩溃 并且表现符合预期。

我没有看到任何错误被写入输出 window 所以我完全不知所措。

这里最有可能的罪魁祸首是将空值作为命令参数传入。您可以尝试使命令使用可为 null 的 int,如下所示:

public class FooViewModel
{
    public FooViewModel()
    {
        // Prevent execution of null int
        MyCommand = new DelegateCommand<int?>(OnMyCommandExecuted, p => p != null);
    }
}

至于异常,这可能是因为您在导航到新视图时没有检查 NavigationResult。您可以如下所示轻松执行此操作:

var result = await NavigationService.NavigateAsync("Foo");

if(!result.Success)
{
    Console.WriteLine(result.Exception);
    System.Diagnostics.Debugger.Break();
}