Convert String to type of Page?

2019-07-30 03:29发布

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

2条回答
祖国的老花朵
2楼-- · 2019-07-30 04:16

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.

查看更多
兄弟一词,经得起流年.
3楼-- · 2019-07-30 04:21

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.

查看更多
登录 后发表回答