Xamarin forms DisplayAlert not showing when called from a function called by a delegate
Solution 1
Is NameReceived fired inside GetName function?
Maybe you need to put app.FB.GetName() after the "+={...};" block.
If nameReceived is correctly fired maybe Greet is not running on ui thread, try wrap your display code in
Device.BeginInvokeOnMainThread (() => {
DisplayAlert("Hey " + name, "Welcome", "OK");
});
as described here
Solution 2
Why don't you create a PageBase
class that implements DisplayAlert
and wraps it in BeingInvokeOnMainThread
so that you do not have to keep re-writing it:
public class PageBase : ContentPage
{
public void DisplayAlert(string message,string title, string button)
{
Device.BeginInvokeOnMainThread (() => {
DisplayAlert(message, title, button);
});
}
}
koreus737
Updated on July 24, 2022Comments
-
koreus737 almost 2 years
When I call Greet from inside the size function DisplayAlert displays an alert as expected However when it is called from the delegate after an event it will Log to the output with the correct name (Greet Has been Called) but the DisplayAlert does not show.
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"); } }
The Code above outputs "Hey Test" and then an alert comes up saying "Hey Test, Welcome" with an OK button then it outputs "Hey Leo" (which is correct because that is the name from the Facebook account) but then no Alert shows.
-
koreus737 almost 9 yearsThanks Mauro this worked! NameRecieved is fired inside GetName and although it works with the code in either order (Maybe there is a delay for the event being fired?) you are right that I should subscribe to the event first. After wrapping my display code in the UI thread it all works, i'm a little new to multithreading so it didn't cross my mind. Cheers, Leo.
-
koreus737 almost 9 yearsGood idea! This makes it much simpler if I want more than one display alert.