Bimo
Bimo

Reputation: 6627

UWP: How to get list of all Page Objects and the corresponding TypeName in the Assembly

In UWP, How do I get a list of all the Page Objects and their corresponding string name in the Assembly. For Example, if I create a Page called Page1, Page2, and Page3 and populate these pages with XAML with controls, how can I can I dynamically create a list of all Page Objects and their corresponding string name?

I have some code that works for WPF and I want to know how to do something similar in UWP:

class MyPage : Page {
public List<Uri> GetXamlFiles()
{
    var pages = new List<Uri>();
    var asm = System.Reflection.Assembly.GetExecutingAssembly();
    Stream stream = asm.GetManifestResourceStream(
        asm.GetName().Name + ".g.resources");

    DataContext = pages;

    using (var reader = new System.Resources.ResourceReader(stream))
    {
        foreach (System.Collections.DictionaryEntry entry in reader)
        {
            pages.Add(new Uri(((string)entry.Key).Replace(".baml", ".xaml"),
                UriKind.Relative));
        }
    }
    return pages;
}

public ObservableCollection<TXamlPage> XamlPages = null;

private void Page_Loaded(object sender, RoutedEventArgs e)
{
        List<Uri> pages = GetXamlFiles();

        XamlPages.Clear();
        foreach (var uri in pages)
        {
            XamlPages.Add(new TXamlPage { uri = uri, Name = System.IO.Path.GetFileName(uri.LocalPath)});
        }
        A1ListBoxPages.ItemsSource = pages;
    }

} //class

public class TXamlPage
{
    public string Name;
    public Uri uri;

    public override string ToString()
    {
        if (Name == null) return "<null>";
        return Name;
    }
}

Upvotes: 1

Views: 574

Answers (1)

Martin Zikmund
Martin Zikmund

Reputation: 39092

You could just search for all types deriving from Page:

private IEnumerable<TypeInfo> GetAllPageTypes()
{
    var currentAssembly = this.GetType().GetTypeInfo().Assembly;
    var pageTypeInfo = typeof(Page).GetTypeInfo();
    return currentAssembly.DefinedTypes.Where(t => pageTypeInfo.IsAssignableFrom(t)).ToList();
}

Upvotes: 2

Related Questions