c# - 在 win 10 通用应用程序中使用 mvvm-light 导航服务时,无法将页面类型的对象转换为类型 'Windows.UI.Xaml.Controls.Frame'

标签 c# xaml mvvm-light win-universal-app

我在新的 Windows 10 通用应用程序 C#/XAML 上遇到以下错误:

GalaSoft.MvvmLight.Platform.dll 中发生了“System.InvalidCastException”类型的异常,但未在用户代码中处理 附加信息:无法将“”类型的对象转换为类型“Windows.UI.Xaml.Controls.Frame”。

在我页面的 View 模型之一中执行以下导航命令:

 _navigationService.NavigateTo(ViewModelLocator.MedicineBoxPageKey);

我正在尝试使用汉堡菜单样式的导航(请参阅 this sample)。 Microsoft 的应用程序上如何执行此操作的示例)到:

1- 在我的所有页面上共享一个方便的解决方案。上面提到的示例使用 AppShell 页面作为应用程序的根而不是框架,它封装了导航菜单和后退按钮的一些行为。那将是理想的。

2- 使用 MVVM-Light 导航服务方便地处理来 self 的 View 模型的所有导航。

以下是 App.xml.Cs 如何在启动时初始化 shell 页面:

    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();

这是 AppShell 类定义:

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

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

从我到目前为止的尝试来看,mvvm-light 导航服务仅在应用程序的根目录中使用框架并记录页面时才有效(否则我们会遇到此转换错误)。 但是,使用框架似乎也不是一种选择,因为正如示例应用程序所说:

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.

我还尝试覆盖 mvvm-light 导航服务的 navigationTo 方法,但错误似乎在我捕捉到它之前就发生了。

有没有人有使用 mvvm-light 导航服务和 shell 页面作为应用根目录(管理汉堡菜单等)的解决方案?

非常感谢!

最佳答案

我与 Laurent Bugnion 进行了交谈,他建议我实现自己的导航服务来处理导航。为此,我制作了一个 PageNavigationService,它实现了 MVVM Light 的 INavigationService 接口(interface)。

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);
        }
    }
}

基本上这是他的实现的副本。但我没有解析为框架,而是解析为 AppShell 并使用 AppFrame 属性进行导航。

我将其放入我的 ViewModelLocator。而不是:

var navigationService = new NavigationService();

我只会使用:

var navigationService = new PageNavigationService();

编辑:我注意到当您使用新的导航服务导航后使用后退键时,NavMenuListView 中出现异常,因为所选项目为空。我通过调整 SetSelectedItem 方法并在转换后的 for 循环中添加 nullcheck 来修复它:

    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;
            }
        }
    }

但可能有比这更优雅的解决方案。

关于c# - 在 win 10 通用应用程序中使用 mvvm-light 导航服务时,无法将页面类型的对象转换为类型 'Windows.UI.Xaml.Controls.Frame',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32132933/

相关文章:

c# - 错误 MySql 您的 SQL 语法有误。添加带有变量的参数时

c# - 适用于 Windows 窗体的 HwndHost - Win32/WinForm 互操作性

c# - c#中需要接口(interface)

silverlight - Mvvm-Light Silverlight,使用带有 Combobox 的 EventToCommand

C# 使用 Ajax 在登录到 Azure AD 后从后端获取数据

c# - WP7 ListBox ItemContainerStyle XAML 禁用不工作

wpf - 在另一个双资源中引用双资源

c# - 从 wpf 资源绑定(bind)文本 block 文本

wpf - 在 WPF 中使用 MVVM 在 View 之间导航

WPF DataGrid ContextMenu 命令绑定(bind)到 MVVMLight RelayCommand<T> 并不总是有效