Xamarin 表单 DisplayAlert 在从委托调用的函数调用时不显示

Xamarin forms DisplayAlert not showing when called from a function called by a delegate

当我从 size 函数内部调用 Greet 时,DisplayAlert 会按预期显示警报但是,当在事件发生后从委托中调用它时,它将使用正确的名称(Greet 已被调用)记录到输出,但 DisplayAlert不显示。

   public class CustomPage : ContentPage
   {
         ...

        protected override void OnValidSizeAllocated(double width, double height)
        {
            ...

            Greet("Test");

            app.FB.GetName();

            app.FB.NameRecieved += (s,e) =>
            {
                Greet(e.Name);  
            };

        }

        public void Greet(string name)
        {
            Utils.Log("Hey " + name);
            DisplayAlert("Hey " + name, "Welcome", "OK");
        }

    }

上面的代码输出 "Hey Test" 然后出现一个警告说 "Hey Test, Welcome" 和一个 OK 按钮然后它输出 "Hey Leo" (这是正确的因为这是来自 Facebook 的名字帐户),但没有显示警报。

NameReceived 是否在 GetName 函数中触发?

也许你需要在“+={...};”之后加上 app.FB.GetName()堵塞。

如果 nameReceived 被正确触发,可能 ui 线程上的 Greet 不是 运行, 尝试将显示代码包装在

Device.BeginInvokeOnMainThread (() => {
 DisplayAlert("Hey " + name, "Welcome", "OK");
});

如描述here

你为什么不创建一个 PageBase class 来实现 DisplayAlert 并将其包装在 BeingInvokeOnMainThread 中,这样你就不必继续重写它:

public class PageBase : ContentPage
{        
    public void DisplayAlert(string message,string title, string button)
    {
         Device.BeginInvokeOnMainThread (() => {
              DisplayAlert(message, title, button);
              });
    }

}