NavigationService throws NullReferenceException

2019-07-12 13:07发布

问题:

Using MVVM Light, I'm trying to develop a rather simple WP7 application. I've run into a problem using the navigation service. I can navigate to a page, but after pressing the back button I can't navigate to the same page again. NavigationService throws a NullReferenceException.

I have implemented my navigation using Messaging from the GalaSoft.MvvmLight.Messaging namespace. All my views inherits from a customized PhoneApplicationPage base class that registrers a listener on "NavigationRequest":

public class PhoneApplicationPage : Microsoft.Phone.Controls.PhoneApplicationPage
{
    public PhoneApplicationPage() : base()
    {
        Messenger.Default.Register<Uri>(this, "NavigationRequest", (uri) => NavigationService.Navigate(uri));
    }
}

From my view models I post Uri's to this listener:

SendNavigationRequestMessage(new Uri("/View/AppSettingsView.xaml", UriKind.Relative));

Like i said, this works except when navigating after pressing the Back button. Why is this and how can I solve it?

Is there a better way to implement navigation using MVVM Light?

回答1:

I'm using MVVM Light as well. I have a class called PageConductor, which is based on what John Papa (Silverlight MVP) from Microsoft uses. Here's the PageConductor Service I use

public class PageConductor : IPageConductor
{
    protected Frame RootFrame { get; set; }

    public PageConductor()
    {
        Messenger.Default.Register<Messages.FrameMessage>(this, OnReceiveFrameMessage);
    }
    public void DisplayError(string origin, Exception e, string details)
    {
        string description = string.Format("Error occured in {0}. {1} {2}", origin, details, e.Message);
        var error = new Model.Error() { Description = description, Title = "Error Occurred" };
        Messenger.Default.Send(new Messages.ErrorMessage() { Error = error });
    }

    public void DisplayError(string origin, Exception e)
    {
        DisplayError(origin, e, string.Empty);
    }
    private void OnReceiveFrameMessage(Messages.FrameMessage msg)
    {
        RootFrame = msg.RootFrame;
    }
    private void Go(string path, string sender)
    {
        RootFrame.Navigate(new Uri(path, UriKind.Relative));
    }
    public void GoBack()
    {
        RootFrame.GoBack();
    }
}

In my MainPage.xaml.cs constructor, I have this, which creates an instance of my ContentFrame in my PageConductor service.:

Messenger.Default.Send(new Messages.FrameMessage() { RootFrame = ContentFrame });

I then use dependency injection to instantiate an instance of my PageConductor Service into my MainPage ViewModel. Here is my MainViewModel class:

protected Services.IPageConductor PageConductor { get; set; }
    public RelayCommand<string> NavigateCommand { get; set; }

    public MainViewModel(Services.IPageConductor pageConductor)
    {

        PageConductor = pageConductor;
        RegisterCommands();
    }
    private void RegisterCommands()
    {
        NavigateCommand = new RelayCommand<string>(
            (source) => OnNavigate(source));

    }
    private void OnNavigate(string sender)
    {
        PageConductor.GoToView(sender, "main");
    }

Notice the instance of my PageConductorService as a parameter in my MainViewModel constructor method. I pass this in via my ViewModelLocator:

private readonly TSMVVM.Services.ServiceProviderBase _sp;
public ViewModelLocator()
{
    _sp = Services.ServiceProviderBase.Instance;
CreateMain(_sp);
}
        #region MainPageViewModel
    public static MainViewModel MainStatic
    {
        get
        {
            Services.ServiceProviderBase SP = Services.ServiceProviderBase.Instance;
            if (_main == null)
            {
                CreateMain(SP);
            }

            return _main;
        }
    }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Performance",
         "CA1822:MarkMembersAsStatic",
         Justification = "This non-static member is needed for data binding purposes.")]
    public MainViewModel Main
    {
        get
        {
            return MainStatic;
        }
    }

    public static void ClearMain()
    {
        _main.Cleanup();
        _main = null;
    }

    public static void CreateMain(Services.ServiceProviderBase SP)
    {
        if (_main == null)
        {
            _main = new MainViewModel(SP.PageConductor);
        }
    }
    #endregion

For further reference, my Messages.FrameMessage class is simply:

internal class FrameMessage
{
    public Frame RootFrame { get; set; }
}

I've had no issues with forward/back buttons.