0

I use Modern UI in my project. Unfortunately, its navigation mechanics are based on absolute (or relative to project directory) paths to views' xaml files.

Example window xaml

...
<mui:LinkGroup DisplayName="Menu">
    <mui:LinkGroup.Links>
    <mui:Link DisplayName="About"
          Source="/View/Pages/AboutView.xaml"/>
    <mui:Link DisplayName="Settings"
          Source="/View/Pages/SettingsView.xaml"/>
    <mui:Link DisplayName="Gallery"
          Source="/View/Pages/GalleryView.xaml"/>
    </mui:LinkGroup.Links>
</mui:LinkGroup>
...

Example code behind

string url = "/View/Pages/AboutView.xaml";
NavigationService nav = NavigationService.GetNavigationService(this);
nav.Navigate(new System.Uri(url, UriKind.RelativeOrAbsolute));

I like to refactor a lot, so I don't want to rely on hardcoded paths to source files. I've been thinking maybe a global dictionary-like structure that maps class types typeof(XyzViewModel) to their respective paths would be a neat idea (at least I'd have everything in one place), but then again, singletons are evil. I don't think reflection is an answer too.

Is there a way to handle this situation without resorting to anti-patterns?

matt-pielat
  • 1,659
  • 3
  • 20
  • 33

1 Answers1

1

There aren't many refactoring save ways to do it.

One thing you can do is use a class with constants, containing all of your paths.

namespace MyApp.Shared 
{
    public static class NavigationConstants
    {
        public const string About = "/View/Page/AboutView.xaml";
    }
}

and then use it in code behind instead of magic strings: nav.Navigate(new System.Uri(NavigationConstants.About, UriKind.RelativeOrAbsolute));

It's not singleton pattern and won't be in the way in terms of decoupling or unit testing.

On the XAML side you can use the Static keyword to map the path.

   xmlns:shared="clr-namespace:MyApp.Shared"
...
<mui:LinkGroup DisplayName="Menu">
    <mui:LinkGroup.Links>
        <mui:Link DisplayName="About"
            Source="{x:Static shared:NavigationConstants.About}"/>
        <mui:Link DisplayName="Settings"
            Source="{x:Static shared:NavigationConstants.Settings}"/>
        <mui:Link DisplayName="Gallery"
            Source="{x:Static shared:NavigationConstants.Gallery}"/>
    </mui:LinkGroup.Links>
</mui:LinkGroup>
Tseng
  • 61,549
  • 15
  • 193
  • 205