Xamarin Forms Error Handling - Messaging Center Al

2019-08-23 05:24发布

问题:

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 View Model

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 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.

回答1:

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