Convert String to type of Page?

2019-07-30 03:26发布

问题:

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.