user10139954
user10139954

Reputation:

How to navigate from custom renderer to content page in xamarin forms

I want to navigate from custom renderer to xamarin forms content page. I am using custom renderer for creating map, when i click on the marker, I need to redirect to it's details page. I am used this link to develop my map-: https://learn.microsoft.com/en-us/xamarin/xamarin-forms/app-fundamentals/custom-renderer/map/customized-pin

void OnInfoWindowClick (object sender, GoogleMap.InfoWindowClickEventArgs e)
  {
   var customPin = GetCustomPin (e.Marker);
     if (customPin == null) 
     {
     throw new Exception ("Custom pin not found");
     }
   else
   {
    // navigate to details page , that is  a content page in xamarin forms.
   }
}

here is my custom pin and details

enter image description here

Upvotes: 0

Views: 1255

Answers (1)

Markus Michel
Markus Michel

Reputation: 2299

You have several options:

MessagingCenter

In the constructor of your App.xaml.cs register with

MessagingCenter.Subscribe<App, CustomModelClass>(App.Current, "OpenPage", (snd, arg) =>
        {
            Device.BeginInvokeOnMainThread(() => { 
                MainPage.Navigation.PushAsync(new ContentPage(arg));
            });
        });

In your renderer then call

MessagingCenter.Send<App, CustomModelClass>(App.Current as App, "OpenPage", model);

Note that CustomModelClass can be any class you define, be it a complex model or just a string.

Static property in App.xaml.cs

Create a property in your App.xaml.cs

    public NavigationPage NavigationPage
    {
        get
        {
            if (MainPage == null)
                return null;

            if (MainPage is MasterDetailPage && (MainPage as MasterDetailPage).Detail is NavigationPage)
                return (MainPage as MasterDetailPage).Detail as NavigationPage;
            else if (MainPage is NavigationPage)
                return (MainPage as NavigationPage);
        }
    }

However, that might be considered kind of "hacky" also you have to ensure that the Mainpage always contains the right page.

However, in your custom renderer you can now call:

(App.Current as App).NavigationPage.Navigation.PushAsync(new ContentPage());

or whatever page you want to push.

Upvotes: 1

Related Questions