【问题标题】:Is it impossible to cast a string representation of a Page to a Page type?是否不可能将 Page 的字符串表示形式转换为 Page 类型?
【发布时间】:2012-12-20 13:06:27
【问题描述】:

我的 App.xaml.cs “永远”的 OnLaunched() 事件中有此代码:

        if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
        {
            if ((roamingSettings.Values.ContainsKey("CurrentPageType")) &&
                (roamingSettings.Values.ContainsKey("CurrentPageParam")))
            {
                rootFrame.Navigate((Type)roamingSettings.Values["CurrentPageType"],
                                         roamingSettings.Values["CurrentPageParam"]);
            }
        }

...但我猜它实际上是第一次运行(执行状态已终止),因为我得到了这个错误消息:

System.InvalidCastException 未被用户代码处理 H结果=-2147467262 Message=无法将“System.String”类型的对象转换为“System.Type”类型。

我在每个页面的 OnNavigatedTo() 事件中将当前页面分配给此漫游设置:

App.roamingSettings.Values["CurrentPageType"] = GetType().ToString();

是我的语法有问题,还是我的方法有问题?

我想我可以这样分配它:

App.roamingSettings.Values["CurrentPageType"] = "DetailPage";

...然后在我的 OnLaunched() 事件中使用它:

if (roamingSettings.Values["CurrentPageType"] == "DetailPage")
{
    Frame.Navigate(typeof(DetailPage), App.activeSection);
}
else if (. . . etc. . . .)

...但我正试图变得更“优雅”... ) 为这些漫游设置保存的值是可见的)。

更新

看了这个,并考虑到那些不带 arg 的页面,我将代码更改为:

        if (args.PreviousExecutionState == ApplicationExecutionState.Terminated)
        {
            if (roamingSettings.Values.ContainsKey("CurrentPageType"))
            {
                if (roamingSettings.Values.ContainsKey("CurrentPageParam"))
                {
                    rootFrame.Navigate((Type)roamingSettings.Values["CurrentPageType"],
                                             roamingSettings.Values["CurrentPageParam"]);
                }
                else
                {
                    rootFrame.Navigate((Type) roamingSettings.Values["CurrentPageType"];
                }
            }
        }

【问题讨论】:

    标签: c# casting windows-8 windows-store-apps


    【解决方案1】:

    试试

    rootFrame.Navigate(Type.GetType(roamingSettings.Values["CurrentPageType"].ToString()),
                                    roamingSettings.Values["CurrentPageParam"]);
    

    【讨论】:

    • 当心您序列化为 CurrentPageParam 的内容,一些简单类型(例如 TimeSpan)似乎是可序列化的,但与 Settings.Values 字典序列化程序不兼容。
    猜你喜欢
    • 2012-06-11
    • 2016-12-08
    • 1970-01-01
    • 1970-01-01
    • 2012-01-06
    • 1970-01-01
    • 2018-01-23
    • 1970-01-01
    • 2010-11-02
    相关资源
    最近更新 更多