简体   繁体   中英

Cannot navigate back in Template10

I'm trying to navigate back to my MainPage from this secondary page. I tried to use NavigationService.GoBack() but I got NullReferenceException .

I didn't change anything from the viewmodel. What I intended to do is to save user input into SQLite first, then navigate back to MainPage

Here is my code from DetailPage.xaml.cs

    private SQLiteService database = new SQLiteService();
    DetailPageViewModel vm = new DetailPageViewModel();

    public DetailPage()
    {
        InitializeComponent();
        NavigationCacheMode = NavigationCacheMode.Disabled;
    }

    private void yesButton_Click(object sender, Windows.UI.Xaml.RoutedEventArgs e)
    {            
        var _name = Name.Text;
        var _uptake = UptakeTime.SelectedIndex + 1; // database index Morning start at 1
        var _intake = int.Parse(Intake.Text);

        vm.ProcessData(_name, _intake, _uptake);
    }

Here is the DetailPageViewModel.cs

    SQLiteService database = new SQLiteService();

    public DetailPageViewModel()
    {
        if (Windows.ApplicationModel.DesignMode.DesignModeEnabled)
        {
            Value = "Designtime value";
        }
    }

    private string _Value = "Default";
    public string Value { get { return _Value; } set { Set(ref _Value, value); } }

    public override async Task OnNavigatedToAsync(object parameter, NavigationMode mode, IDictionary<string, object> state)
    {
        Value = (state.ContainsKey(nameof(Value))) ? state[nameof(Value)]?.ToString() : parameter?.ToString();
        await Task.CompletedTask;
    }

    public override async Task OnNavigatedFromAsync(IDictionary<string, object> pageState, bool suspending)
    {
        if (suspending)
        {
            pageState[nameof(Value)] = Value;
        }
        await Task.CompletedTask;
    }

    public override async Task OnNavigatingFromAsync(NavigatingEventArgs args)
    {
        args.Cancel = false;
        await Task.CompletedTask;
    }

    public void GotoMainPage() =>
        NavigationService.GoBack();    

    public void ProcessData(string _name, int _type, int _uptake)
    {
        database.AddNewItem(_name, _uptake, _type);
        GotoMainPage();
    }

Side note : I tried to access the GotoMainPage from Detail.xaml.cs by using vm.GotoMainPage() , but it still returned exception

  • To navigate between different Pages use the Frame.Navigate method.
  • An example for page Navigation to a xaml Page called Mainpage is: this.Frame.Navigage(typeof(Mainpage));

For further Information look at the Documentation: Frame.Navigate

The Namespace being used is called System.Windows.Controls .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM