Skip to content

Instantly share code, notes, and snippets.

@nodoid
Created November 13, 2018 15:24
Show Gist options
  • Save nodoid/5abcceae070a98a7f44e966584bd5aa6 to your computer and use it in GitHub Desktop.
Save nodoid/5abcceae070a98a7f44e966584bd5aa6 to your computer and use it in GitHub Desktop.
forms navservice for mvvmlvght
public class NavigationService : INavigationService
{
readonly Dictionary<string, Type> _pagesByKey = new Dictionary<string, Type>();
NavigationPage _navigation;
public string CurrentPageKey
{
get
{
lock (_pagesByKey)
{
if (_navigation.CurrentPage == null)
{
return null;
}
var pageType = _navigation.CurrentPage.GetType();
return _pagesByKey.ContainsValue(pageType)
? _pagesByKey.First(p => p.Value == pageType).Key
: null;
}
}
}
public void GoBack()
{
Device.BeginInvokeOnMainThread(() => _navigation.PopAsync());
}
public void NavigateTo(string pageKey)
{
NavigateTo(pageKey, null);
}
public void NavigateTo(string pageKey, object parameter)
{
lock (_pagesByKey)
{
if (_pagesByKey.ContainsKey(pageKey))
{
var type = _pagesByKey[pageKey];
ConstructorInfo constructor;
object[] parameters;
if (parameter == null)
{
constructor = type.GetTypeInfo()
.DeclaredConstructors
.FirstOrDefault(c => !c.GetParameters().Any());
parameters = new object[]
{
};
}
else
{
constructor = type.GetTypeInfo()
.DeclaredConstructors
.FirstOrDefault(
c =>
{
var p = c.GetParameters();
return p.Count() == 1
&& p[0].ParameterType == parameter.GetType();
});
parameters = new[]
{
parameter
};
}
if (constructor == null)
{
throw new InvalidOperationException(
"No suitable constructor found for page " + pageKey);
}
var page = constructor.Invoke(parameters) as Page;
_navigation.PushAsync(page);
}
else
{
throw new ArgumentException(
string.Format(
"No such page: {0}. Did you forget to call NavigationService.Configure?",
pageKey),
"pageKey");
}
}
}
public void Configure(string pageKey, Type pageType)
{
lock (_pagesByKey)
{
if (_pagesByKey.ContainsKey(pageKey))
{
_pagesByKey[pageKey] = pageType;
}
else
{
_pagesByKey.Add(pageKey, pageType);
}
}
}
public void Initialize(NavigationPage navigation)
{
_navigation = navigation;
navigation.BarBackgroundColor = Color.FromHex("022330");
navigation.BarTextColor = Color.White;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment