loo*_*oop 1 c# navigation windows-8 windows-store-apps
我想将字符串DashBoard转换为一种名为DashBoard的页面,因为我想在导航中使用它.通常我会导航到这样的页面
this.Frame.Navigate(typeof(DashBoard));
Run Code Online (Sandbox Code Playgroud)
但我想将DashBoard页面替换为这样的变量
this.Frame.Navigate(typeof(Somestring));
Run Code Online (Sandbox Code Playgroud)
你可以使用Type.GetType(string) [MSDN]
this.Frame.Navigate(Type.GetType(My.NameSpace.App.DashBoard,MyAssembly));
Run Code Online (Sandbox Code Playgroud)
阅读有关如何格式化字符串的备注部分.
或者你可以使用反射:
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();
}
}
Run Code Online (Sandbox Code Playgroud)
这可以使用如下:
private void Button_Click(object sender, RoutedEventArgs e)
{
this.Frame.Navigate(TypeHelper.GetTypeByString("TestPage", this.GetType().GetTypeInfo().Assembly));
}
Run Code Online (Sandbox Code Playgroud)
在这个例子中.该函数将在当前程序集中搜索名为TestPage的页面,然后导航到该页面.
| 归档时间: |
|
| 查看次数: |
1601 次 |
| 最近记录: |