Search code examples
c#wpfresourcedictionarynavigationservice

How to navigate to a xaml page from ResourceDictionary class (WPF)


I have a ResourceDictionary class as follows:

  using System.Windows.Navigation;
    using static myApp.filesXAML.Login;

    namespace myApp.Clases
    {
        partial class functionsMenu : ResourceDictionary
        {
            private void imageCloseMyApp(object sender, MouseButtonEventArgs e)
            {
NavigationService.Navigate(new Uri("filesXAML/Login.xaml", UriKind.Relative));
            }
        }
    }

The imageCloseMyApp function is invoked from an image by clicking on it and I wish to call another page.

And I get the following error before compiling the project:

Severity Code Description Project File Line Status deleted Error CS0120 An object reference is required for the field, method or property 'NavigationService.Navigate (Uri)' not static myApp H:\pro\Visual_Studio\myApp\myApp\Classes\ FunctionsMenu.cs 35 Active

I have searched the internet, and tried the following options:

Login page = new Login();         
page.NavigationService.Navigate(new Uri("filesXAML/Login.xaml",UriKind.RelativeOrAbsolute));

// or

NavigationService nav = NavigationService.GetNavigationService(Application.Current.Windows[0].Parent);
nav.Navigate(new Uri("filesXAML/Login.xaml", UriKind.Relative));

But none works.

Any suggestions or comments?


Solution

  • I have achieved it as follows:

     NavigationService nav = NavigationService.GetNavigationService((Grid)((Image)sender).Parent);
    nav.Navigate(new Uri("filesXAML/Login.xaml", UriKind.Relative));

    I guide myself to understand the following thread:

    How do you get the parent control from an event send by a control in the resources