I have the following projects:
- Cross Platform App (Xamarin.Forms - PCL): "MyApp"
- Class Library (Xamarin.Forms): "MyLibrary"
"MyApp" references the "MyLibrary" assembly. "MyLibrary" contains various methods that interface with our "in-house" Authentication WebAPI. I've managed to get the authentication working- but now I would like to affect our app's UI from within the class library...
How can I (for example) open an alert or change the Application.Current.MainPage from within "MyLibrary"?
I've tried the following:
MyApp - App.xaml.cs
using MyApp.Views;
using Xamarin.Forms;
using Xamarin.Forms.Xaml;
[assembly: XamlCompilation(XamlCompilationOptions.Compile)]
namespace MyApp
{
public partial class App : Application
{
public MyLibrary.MyLibraryThing MyLibraryThing;
public App()
{
MyLibraryThing = new MyLibrary.MyLibraryThing();
InitializeComponent();
SetMainPage();
}
public static void SetMainPage()
{
Current.MainPage = new MainPage();
}
protected override void OnStart()
{
MyLibraryThing.DoSomething();
}
}
}
MyLibrary - MyLibraryThing.cs
using Xamarin.Forms;
namespace MyLibrary
{
public class MyLibraryThing()
{
Application myApp;
public MyLibraryThing(Application application)
{
myApp = application;
}
public void DoSomething()
{
myApp.Current.MainPage = new ContentPage()
{
Content = new Label
{
Text = "Created by MyLibrary.MyLibraryThing.DoSomething()!",
VerticalOptions = LayoutOptions.CenterAndExpand,
HorizontalOptions = LayoutOptions.CenterAndExpand
}
};
}
public async void DoSomethingElse()
{
await myApp.MainPage.DisplayAlert("Alert", "This alert was created by MyLibrary.MyLibraryThing.DoSomethingElse()!", "Cool");
}
}
}
The above produces the following exception:
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> Java.Lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
How can I make my Application object accessible to my external class library?