订阅Xamarin.Forms中的DisplayAlert

时间:2017-06-12 15:35:53

标签: testing xamarin.forms alert messaging

我想在我的应用中的某处调用DisplayAlert时收到通知。 Xamarin.Forms source code建议使用MessagingCenter,因为它使用它在DisplayAlert()内发送消息:

MessagingCenter.Send(this, AlertSignalName, args);

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

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

这是正确的方向吗?或者你有替代解决方案吗?我甚至会考虑一些基于反射的hacky方法,因为我只需要它用于测试目的。

2 个答案:

答案 0 :(得分:0)

This works for me:

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

But it is raised when DisplayAlert is displayed. (I think it's correct...)

This is my page:

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

答案 1 :(得分: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);
});