Xamarin表单错误处理-消息中心警报未从模型中显示 [英] Xamarin Forms Error Handling - Messaging Center Alert not displaying from model

查看:70
本文介绍了Xamarin表单错误处理-消息中心警报未从模型中显示的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试实现从视图模型到视图控制器的错误捕获功能,因此如果出现错误,则会显示一条消息.

I'm trying to implement error trapping functionality from the view model to the view controler, so if there is an error, a message is displayed.

这是我正在使用的代码:

Here is the code i'm using:

ItemsPage视图模型

async Task ExecuteCommand()
  {
   ...
    try
        {
        }
    catch (Exception ex)
        {
            Debug.WriteLine(ex);
            MessagingCenter.Send(new MessagingCenterAlert
            {
                Title = "Error",
                Message = "Unable to load services.",
                Cancel = "OK"
            }, "message");
        }
     finally
        {
            IsBusy = false;
        }

ItemsPage.XAML.cs文件 在页面的构造函数中. ...

ItemsPage.XAML.cs File In the constructor for the page.. ...

public ItemsPage()
    {
        InitializeComponent();
        MessagingCenter.Subscribe<ItemsViewModel, MessagingCenterAlert>
        (this, "message", (sender, arg) => {
            var argu = arg;
            DisplayAlert("Problem","message body" + argu.Message, "OK");

        });

不确定这是否是正确的方法,但是如果出现错误,则不会显示警报.

Not sure if this is the correct way to do this, but it is not displaying the alert if there is an error.

推荐答案

尝试将其包装在对Device.BeginInvokeOnMainThread的调用中,例如:

Try wrapping it in a call to Device.BeginInvokeOnMainThread like:

MessagingCenter.Subscribe<ItemsViewModel, MessagingCenterAlert>
    (this, "message", (sender, arg) => {
        var argu = arg;

        Device.BeginInvokeOnMainThread (() => {
            DisplayAlert("Problem","message body" + argu.Message, "OK");
        });
    });

这篇关于Xamarin表单错误处理-消息中心警报未从模型中显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆