在 Xamarin.Forms 订阅 DisplayAlert

Subscribe to DisplayAlert in Xamarin.Forms

我希望在我的应用程序某处调用 DisplayAlert 时收到通知。 Xamarin.Forms source code 建议使用 MessagingCenter,因为它使用它在 DisplayAlert():

内发送消息
MessagingCenter.Send(this, AlertSignalName, args);

但是我还没有收到任何东西。这是我到目前为止尝试过的线路之一:

MessagingCenter.Subscribe<Page>(this, Page.AlertSignalName, arg => {
    Console.WriteLine("Message received: " + arg);
});

这个方向对吗?或者您有替代解决方案吗?我什至会考虑一些基于反射的骇人听闻的方法,因为我需要它仅用于测试目的。

这对我有用:

MessagingCenter.Subscribe<Page, Xamarin.Forms.Internals.AlertArguments>(this, Page.AlertSignalName, (obj, obj1) => {
    int aa = 0;
});

但是显示DisplayAlert时会引发。 (我认为是正确的...)

这是我的页面:

using System;
using Xamarin.Forms;

namespace Test
{
    public class MyPage : ContentPage
    {
        public MyPage()
        {
            Button b = new Button {Text = "Press" };
            b.Clicked += async (object sender, EventArgs e) => {
                await DisplayAlert("Attention", "AAA", "Ok");
                MessagingCenter.Send<MyPage>(this, "AAA");
            };

            Content = new StackLayout
            {
                Children = {
                    new Label { Text = "Hello ContentPage" },
                    b
                }
            };

            MessagingCenter.Subscribe<MyPage>(this, "AAA", (obj) => {
                int aa = 0;
            });
            MessagingCenter.Subscribe<Page, Xamarin.Forms.Internals.AlertArguments>(this, Page.AlertSignalName, (obj, obj1) => {
                int aa = 0;
            });
        }
    }
}

在 Xamarin source test code(命名空间 Xamarin.Forms.Core.UnitTests)中,它以这样的强类型方式使用:

[Test]
public void DisplayAlert ()
{
    var page = new ContentPage ();

    AlertArguments args = null;
    MessagingCenter.Subscribe (this, Page.AlertSignalName, (Page sender, AlertArguments e) => args = e);

    var task = page.DisplayAlert ("Title", "Message", "Accept", "Cancel");

    Assert.AreEqual ("Title", args.Title);
    Assert.AreEqual ("Message", args.Message);
    Assert.AreEqual ("Accept", args.Accept);
    Assert.AreEqual ("Cancel", args.Cancel);

    bool completed = false;
    var continueTask = task.ContinueWith (t => completed = true);

    args.SetResult (true);
    continueTask.Wait ();
    Assert.True (completed);
}

所以应该这样做:

MessagingCenter.Subscribe(this, Page.AlertSignalName, (Page sender, AlertArguments args) =>
{
    Console.WriteLine("Message received: " + args.Message);
});