Skip to content

Instantly share code, notes, and snippets.

@markjulmar
Last active February 26, 2016 14:34
Show Gist options
  • Save markjulmar/551ff57beb4fa959ccc0 to your computer and use it in GitHub Desktop.
Save markjulmar/551ff57beb4fa959ccc0 to your computer and use it in GitHub Desktop.
using Xamarin.Forms;
using System.Threading.Tasks;
using System;
using System.Collections.Generic;
namespace GreatQuotes.Services
{
public class NavigationService
{
private static readonly Task TaskCompleted = Task.FromResult(0);
readonly Dictionary<string, Func<Page>> registeredPages = new Dictionary<string, Func<Page>>();
public void RegisterPage(string pageKey, Func<Page> creator)
{
if (string.IsNullOrEmpty(pageKey))
throw new ArgumentNullException("pageKey");
if (creator == null)
throw new ArgumentNullException("creator");
registeredPages.Add(pageKey, creator);
}
public void UnregisterPage(string pageKey)
{
if (string.IsNullOrEmpty(pageKey))
throw new ArgumentNullException("pageKey");
registeredPages.Remove(pageKey);
}
Page GetPageByKey(string pageKey)
{
if (string.IsNullOrEmpty(pageKey))
throw new ArgumentNullException("key");
Func<Page> creator;
return registeredPages.TryGetValue(pageKey, out creator) ? creator.Invoke() : null;
}
public Task GotoPageAsync(string pageKey, object viewModel)
{
var page = GetPageByKey(pageKey);
if (page == null)
return TaskCompleted;
if (viewModel != null)
page.BindingContext = viewModel;
return Application.Current.MainPage.Navigation.PushAsync(page);
}
public Task PopAsync()
{
// Ignore if nothing to pop. GotoPageAsync allows no page navigation cases for
// validation and or Master/Detail open/close
return Application.Current.MainPage.Navigation.NavigationStack.Count == 1
? TaskCompleted
: Application.Current.MainPage.Navigation.PopAsync();
}
public Task PushModalAsync(string pageKey, object viewModel = null)
{
var page = GetPageByKey(pageKey);
if (page == null)
throw new ArgumentException("Cannot navigate to unregistered page", "pageKey");
if (viewModel != null)
page.BindingContext = viewModel;
return Application.Current.MainPage.Navigation.PushModalAsync(page);
}
public Task PopModalAsync()
{
return Application.Current.MainPage.Navigation.PopModalAsync();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment