Skip to content

Instantly share code, notes, and snippets.

@codemillmatt
Last active August 25, 2016 11:09
Show Gist options
  • Save codemillmatt/b79c0d6f42995fe259d7084ad6cb4332 to your computer and use it in GitHub Desktop.
Save codemillmatt/b79c0d6f42995fe259d7084ad6cb4332 to your computer and use it in GitHub Desktop.
Example of how to pop to an arbitrary page within the navigation stack using view model first navigation
public void PopTo<T>() where T : BaseViewModel
{
var pagesToRemove = new List<Page>();
var upper = FormsNavigation.NavigationStack.Count - 1;
// Loop through the nav stack backwards
for (int i = upper; i >= 0; i--)
{
var currentPage = FormsNavigation.NavigationStack[i] as IViewFor;
// Stop the whole show if one of the pages isn't an IViewFor
if (currentPage == null)
return;
// If we hit the view model type, break out
if (currentPage.ViewModel.GetType() == typeof(T))
break;
// Finally - always add to the list
pagesToRemove.Add(currentPage as Page);
}
// Remove everything from the stack
foreach (var item in pagesToRemove)
{
FormsNavigation.RemovePage(item);
}
}
@hshaun
Copy link

hshaun commented Aug 25, 2016

Nice, I've figured out but your code looks much cleaner. Whats your comment on my code.

`Type RetrieveView (Type viewModelType)
{
// look up what type of view it corresponds to
var viewType = _viewModelViewDictionary [viewModelType];

        return viewType;
    }

    public async Task<bool> PopToPageAsync (Type viewModelType)
    {
        var viewType = (Type) RetrieveView (viewModelType);

        int i = FormsNavigation.NavigationStack.Count;

        bool pageExist = false;

        foreach (Page current in FormsNavigation.NavigationStack.Reverse()) {
            --i;
            if (current.GetType().Equals(viewType)) {

                int sourceIndex = FormsNavigation.NavigationStack.Count()-1;
                int destinationIndex = i+1;

                while (sourceIndex != destinationIndex) {
                    FormsNavigation.RemovePage (FormsNavigation.NavigationStack [--sourceIndex]);
                }
                pageExist = true;
                break;
            }
        }
        if (pageExist) {
            await FormsNavigation.PopAsync ();
        }
        return pageExist;
    }`

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment