我想将字符串 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/