Unable to cast object of type Page to type 'Wi

2019-04-29 20:59发布

问题:

I m hitting the following error on my new windows 10 universal app C#/XAML:

An exception of type 'System.InvalidCastException' occurred in GalaSoft.MvvmLight.Platform.dll but was not handled in user code Additional information: Unable to cast object of type '' to type 'Windows.UI.Xaml.Controls.Frame'.

on the following navigating command in one of my page's view model:

 _navigationService.NavigateTo(ViewModelLocator.MedicineBoxPageKey);

I am trying to have a hamburger menu style navigation (see this sample). app by Microsoft on an example of how to do this) to:

1- have a convenient solution shared across all my pages. The sample mentioned above uses an AppShell Page as the root of the app instead of a Frame, that encapsulates the navigation menu and some behavior of the back button. That would be ideal.

2- Use the MVVM-Light navigation service to handle all the navigation from my view model conveniently.

Here is how the App.xml.Cs initializes the shell page onLaunched:

    AppShell shell = Window.Current.Content as AppShell;

    // Do not repeat app initialization when the Window already has content,
    // just ensure that the window is active
    if (shell == null)
    {
        // Create a a AppShell to act as the navigation context and navigate to the first page
        shell = new AppShell();
        // Set the default language
        shell.Language = Windows.Globalization.ApplicationLanguages.Languages[0];

        shell.AppFrame.NavigationFailed += OnNavigationFailed;

        if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
        {
            //TODO: Load state from previously suspended application
        }
    }

    // Place our app shell in the current Window
    Window.Current.Content = shell;

    if (shell.AppFrame.Content == null)
    {
        // When the navigation stack isn't restored, navigate to the first page
        // suppressing the initial entrance animation.
        shell.AppFrame.Navigate(typeof(MedicinesStorePage), e.Arguments, new Windows.UI.Xaml.Media.Animation.SuppressNavigationTransitionInfo());
    }

    // Ensure the current window is active
    Window.Current.Activate();

And here is the AppShell class definition:

public sealed partial class AppShell : Page
    {
        public static AppShell Current = null;

        public AppShell()
        {
            this.InitializeComponent();
         }
     }

From what I have tried so far, the mvvm-light navigation service only works when a Frame is used a root of the app and note a Page (otherwise we get this casting bug). However using a Frame does not seem to be a option either since as the sample app puts it:

Using a Page as the root for the app provides a design time experience as well as ensures that when it runs on Mobile the app content won't appear under the system's StatusBar which is visible by default with a transparent background. It will also take into account the presence of software navigation buttons if they appear on a device. An app can opt-out by switching to UseCoreWindow.

I also tried to overide the navigationTo method from the mvvm-light navigation service but the bug seems to occur before I could catch it.

Does anyone has a solution to use the mvvm-light navigation service and a shell page as the app root (that manages the hamburger menu, etc.)?

Thanks a lot!

回答1:

I talked to Laurent Bugnion and he recommended me to implemented my own navigation service who handles the navigation. For this I made a PageNavigationService who implements the INavigationService Interface of MVVM Light.

public class PageNavigationService : INavigationService
{
    /// <summary>
    ///     The key that is returned by the <see cref="CurrentPageKey" /> property
    ///     when the current Page is the root page.
    /// </summary>
    public const string RootPageKey = "-- ROOT --";

    /// <summary>
    ///     The key that is returned by the <see cref="CurrentPageKey" /> property
    ///     when the current Page is not found.
    ///     This can be the case when the navigation wasn't managed by this NavigationService,
    ///     for example when it is directly triggered in the code behind, and the
    ///     NavigationService was not configured for this page type.
    /// </summary>
    public const string UnknownPageKey = "-- UNKNOWN --";

    private readonly Dictionary<string, Type> _pagesByKey = new Dictionary<string, Type>();

    /// <summary>
    ///     The key corresponding to the currently displayed page.
    /// </summary>
    public string CurrentPageKey
    {
        get
        {
            lock (_pagesByKey)
            {
                var frame = ((AppShell) Window.Current.Content).AppFrame;

                if (frame.BackStackDepth == 0)
                {
                    return RootPageKey;
                }

                if (frame.Content == null)
                {
                    return UnknownPageKey;
                }

                var currentType = frame.Content.GetType();

                if (_pagesByKey.All(p => p.Value != currentType))
                {
                    return UnknownPageKey;
                }

                var item = _pagesByKey.FirstOrDefault(
                    i => i.Value == currentType);

                return item.Key;
            }
        }
    }

    /// <summary>
    ///     If possible, discards the current page and displays the previous page
    ///     on the navigation stack.
    /// </summary>
    public void GoBack()
    {
        var frame = ((Frame) Window.Current.Content);

        if (frame.CanGoBack)
        {
            frame.GoBack();
        }
    }

    /// <summary>
    ///     Displays a new page corresponding to the given key.
    ///     Make sure to call the <see cref="Configure" />
    ///     method first.
    /// </summary>
    /// <param name="pageKey">
    ///     The key corresponding to the page
    ///     that should be displayed.
    /// </param>
    /// <exception cref="ArgumentException">
    ///     When this method is called for
    ///     a key that has not been configured earlier.
    /// </exception>
    public void NavigateTo(string pageKey)
    {
        NavigateTo(pageKey, null);
    }

    /// <summary>
    ///     Displays a new page corresponding to the given key,
    ///     and passes a parameter to the new page.
    ///     Make sure to call the <see cref="Configure" />
    ///     method first.
    /// </summary>
    /// <param name="pageKey">
    ///     The key corresponding to the page
    ///     that should be displayed.
    /// </param>
    /// <param name="parameter">
    ///     The parameter that should be passed
    ///     to the new page.
    /// </param>
    /// <exception cref="ArgumentException">
    ///     When this method is called for
    ///     a key that has not been configured earlier.
    /// </exception>
    public void NavigateTo(string pageKey, object parameter)
    {
        lock (_pagesByKey)
        {
            if (!_pagesByKey.ContainsKey(pageKey))
            {
                throw new ArgumentException(
                    string.Format(
                        "No such page: {0}. Did you forget to call NavigationService.Configure?",
                        pageKey),
                    "pageKey");
            }

            var shell = ((AppShell) Window.Current.Content);
            shell.AppFrame.Navigate(_pagesByKey[pageKey], parameter);
        }
    }

    /// <summary>
    ///     Adds a key/page pair to the navigation service.
    /// </summary>
    /// <param name="key">
    ///     The key that will be used later
    ///     in the <see cref="NavigateTo(string)" /> or <see cref="NavigateTo(string, object)" /> methods.
    /// </param>
    /// <param name="pageType">The type of the page corresponding to the key.</param>
    public void Configure(string key, Type pageType)
    {
        lock (_pagesByKey)
        {
            if (_pagesByKey.ContainsKey(key))
            {
                throw new ArgumentException("This key is already used: " + key);
            }

            if (_pagesByKey.Any(p => p.Value == pageType))
            {
                throw new ArgumentException(
                    "This type is already configured with key " + _pagesByKey.First(p => p.Value == pageType).Key);
            }

            _pagesByKey.Add(
                key,
                pageType);
        }
    }
}

Basicly it's a copy of his implementation. But instead of parsing to a Frame I parse to an AppShell and use the AppFrame Property to navigate.

I put this to my ViewModelLocator. Instead of:

var navigationService = new NavigationService();

I will just use:

var navigationService = new PageNavigationService();

EDIT: I Noticed that there is an excpetion in the NavMenuListView when you use the backkey after you navigated with the new navigationservice since the selected item is null. I fixed it with adjusting the SetSelectedItem Method and adding a nullcheck in the for loop after the cast:

    public void SetSelectedItem(ListViewItem item)
    {
        var index = -1;
        if (item != null)
        {
            index = IndexFromContainer(item);
        }

        for (var i = 0; i < Items.Count; i++)
        {
            var lvi = (ListViewItem) ContainerFromIndex(i);

            if(lvi == null) continue;

            if (i != index)
            {
                lvi.IsSelected = false;
            }
            else if (i == index)
            {
                lvi.IsSelected = true;
            }
        }
    }

But there might be a more elegant solution than this.