【问题标题】:Xamarin forms DisplayAlert not showing when called from a function called by a delegate从委托调用的函数调用 Xamarin 窗体 DisplayAlert 时不显示
【发布时间】:2015-09-26 08:59:23
【问题描述】:

当我从 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 帐户中的名称)但是然后没有警报显示。

【问题讨论】:

  • 您(可能)需要强制 DisplayAlert 在 UI 线程上运行。尝试使用 Device.BeginInvokeOnMainThread()

标签: c# android ios xamarin delegates


【解决方案1】:

您为什么不创建一个实现DisplayAlert 的PageBase 类并将其包装在BeingInvokeOnMainThread 中,这样您就不必一直重写它:

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

}

【讨论】:

  • 好主意!如果我想要多个显示警报,这会变得更加简单。
【解决方案2】:

NameReceived 是否在 GetName 函数中触发?

也许您需要将 app.FB.GetName() 放在“+={...};”之后堵塞。

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

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

如here所述

【讨论】:

  • 感谢 Mauro 成功了! NameRecieved 在 GetName 内被触发,尽管它以任一顺序与代码一起工作(也许触发的事件有延迟?)你是对的,我应该首先订阅该事件。在将我的显示代码包装在 UI 线程中之后,一切正常,我对多线程有点陌生,所以我并没有想到它。干杯,狮子座。
猜你喜欢
  • 2020-04-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-09-20
  • 2021-05-31
  • 1970-01-01
  • 2012-09-30
相关资源
最近更新 更多