Search code examples
c#uwpuwp-navigation

How can I use UWP Frame.Navigate() based on a string value


First off, I have looked at all the suggested questions and none of them actually answer my question. I see solutions for WinRT or WPF but none that work with UWP.

With that being said, I am looking for a way to do something like this:

private void ListView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var pageName = ((ListViewItem)((ListView)sender).SelectedItem).Name;
            var pageObj = ???? //Some way to ref MyNamespace.MyPage.xaml
            MyFrame.Navigate(typeof(pageObj));
        }

I have tried to use all combinations of the following:

var pageObj = FindName(pageName);
---
var pageObj = System.Type.GetType(this.GetType().Namespace + "." + pageName);
---
MyFrame.Navigate(typeof(pageObj));
---
MyFrame.Navigate(pageObj);
---
MyFrame.Navigate(typeof(pageName));
---
MyFrame.Navigate(pageName);

And some otherthings I cant quite remember. At best I get a NullReferenceException.

I am fairly new to c# and UWP, so if this is something that is not possible I am sorry for wasting your time. It's just that if I decide to add a new page at some point I don't want to have to edit some switch statement; I just want to add a new ListViewItem and be done with it.

Also, its a learning experience for me. I know how to do switch statements already. Now I would like to do something a little more elegant.

Thank you in advance for any help provided!


Solution

  • If you just want to get the page type by your listviewitem string value, it's impossible. You would have to manually specify the page type for navigation.

    For example, like you said, you could use Switch statements.

    Or if you're familiar with WindowsTemplateStudio, you could make an attached property(NavigateTo) and a NavigationService helper class. You could use the attached property on your XAML and get the page type by the attached property value like this:

    var pageType = menuItem.GetValue(NavHelper.NavigateToProperty) as Type;
    

    If you do not understand what this code is doing, I suggested that you use the WindowsTemplateStudio to create a simple code project and add some break points to debug its code and understand the whole navigation process.