c# - 将字符串转换为页面类型?

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

我想将字符串 DashBoard 转换为一种名为 DashBoard 的页面类型,因为我想将它用于导航目的。通常我导航到这样的页面

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

但我想将 DashBoard 页面替换为这样的变量

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

最佳答案

您可以使用 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 的页面,然后导航到该页面。

关于c# - 将字符串转换为页面类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18056433/

相关文章:

c# - ASP.NET MVC Helpers,将两个对象 htmlAttributes 合并在一起

c# - 如何在 Prism 中设置 ServiceLocationProvider 进行单元测试导航?

c# - gridview C# 中滚动查看器的水平偏移

emacs - 命令在emacs上围绕光标水平居中屏幕?

c# - 正则表达式 - 在字符串中查找 4 位数字

javascript - Windows 8 Javascript 应用程序激活/启动延迟

c++ - 在 Windows 8 上使用 Windows UI 自动化列出 Metro 应用程序的所有 UI 元素

javascript - 实现 NavigationView 时出现问题 - Sc.View 不可观察

android - 在 Android API 10 中实现横向导航

c# - 我应该使用 WCF 来实现给定的二进制网络协议(protocol)吗?