将字符串转换为页面类型? [英] Convert String to type of Page?
本文介绍了将字符串转换为页面类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想将字符串 DashBoard 转换为名为 DashBoard 的页面类型,因为我想在导航中使用它.通常我会导航到这样的页面
I want to Convert a string DashBoard to a type of page named as DashBoard because I wanted to use it in navigation purpose. Normally I navigate to some page like this
this.Frame.Navigate(typeof(DashBoard));
但是我想将DashBoard页面替换为这样的变量
but I want to DashBoard page to be replaced by variable like this
this.Frame.Navigate(typeof(Somestring));
推荐答案
您可以使用Type.GetType(string)
[MSDN]
this.Frame.Navigate(Type.GetType(My.NameSpace.App.DashBoard,MyAssembly));
阅读有关如何设置字符串格式的说明部分.
Read the remarks section on how to format the string.
或者您可以使用反射:
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的页面,然后导航到该页面.
In this example. The function will search in the current assembly for a page with the name TestPage and then navigate to it.
这篇关于将字符串转换为页面类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文