将String转换为Page的类型?

时间:2013-08-05 10:53:54

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

我想将字符串 DashBoard 转换为名为 DashBoard 的页面类型,因为我想在导航中使用它。通常我会导航到这样的页面

this.Frame.Navigate(typeof(DashBoard));

但我希望将DashBoard页面替换为像这样的变量

this.Frame.Navigate(typeof(Somestring));

2 个答案:

答案 0 :(得分:9)

您可以使用Type.GetType(string) [MSDN]

this.Frame.Navigate(Type.GetType(My.NameSpace.App.DashBoard,MyAssembly));

阅读关于如何格式化字符串的备注部分。

或者你可以使用反射:

using System.Linq;
public static class TypeHelper
{
    public static Type GetTypeByString(string type, Assembly lookIn)
    {
        var types = lookIn.DefinedTypes.Where(t => t.Name == type && t.IsSubclassOf(typeof(Windows.UI.Xaml.Controls.Page)));
        if (types.Count() == 0)
        {
            throw new ArgumentException("The type you were looking for was not found", "type");
        }
        else if (types.Count() > 1)
        {
            throw new ArgumentException("The type you were looking for was found multiple times.", "type");
        }
        return types.First().AsType();
    }
}

这可以用作以下内容:

private void Button_Click(object sender, RoutedEventArgs e)
{
    this.Frame.Navigate(TypeHelper.GetTypeByString("TestPage", this.GetType().GetTypeInfo().Assembly));
}

在这个例子中。该函数将在当前程序集中搜索名为TestPage的页面,然后导航到该页面。

答案 1 :(得分:0)

如果您知道DashBoard的完全限定名称 - 即它所在的程序集和命名空间 - 您可以使用反射来确定要传递给Navigate的内容。

根据您的需要,查看the docs for System.Reflection.Assembly,特别是GetTypesGetExportedTypes