Convert String to type of Page?

末鹿安然 提交于 2019-12-11 09:48:23

问题


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));

but I want to DashBoard page to be replaced by variable like this

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

回答1:


You could use the Type.GetType(string) [MSDN]

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

Read the remarks section on how to format the string.

Or you can use reflection:

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();
    }
}

This can be used as following:

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

In this example. The function will search in the current assembly for a page with the name TestPage and then navigate to it.




回答2:


If you know the fully qualified name of DashBoard - i.e. which assembly and namespace it's in - you can use reflection to determine what to pass to Navigate.

Look at the docs for System.Reflection.Assembly, in particular GetTypes and GetExportedTypes, depending on what you need.



来源:https://stackoverflow.com/questions/18056433/convert-string-to-type-of-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!