问题
I'm trying to pass the id of the clicked element as a string to a new page, however the app always crashes. I'm not entirely sure how to find out the cause of the problem as every example I've found uses the same method and it works just fine for them.
The sender event:
private void MovieBox_OnTapped(object sender, TappedRoutedEventArgs e)
{
var id = (sender as StackPanel).Tag as string;
Debug.WriteLine(id); //the correct id in string
Frame.Navigate(typeof(MovieDetailsPage),id);
}
The OnNavigatedTo event
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
string text = e.Parameter as string;
Debug.WriteLine(text);
await Task.CompletedTask;
}
The app crashes somewhere in between it seems like. Putting a breakpoint on the first event shows the correct id being sent, however it never reaches OnNavigatedTo.
I'm not sure what the problem is, as the second page loads just fine if I remove the parameter.
Edit: I wrote the exception from the App.g.i.cs file:
Exception thrown: 'Newtonsoft.Json.JsonReaderException' in MovieLibraryApp.exe
An exception of type 'Newtonsoft.Json.JsonReaderException' occurred in
MovieLibraryApp.exe but was not handled in user code
Unexpected character encountered while parsing value: m. Path '', line 0, position 0.
And here is the xaml (it's kinda a mess atm): https://pastebin.com/GkXkxYDS
Also this:
Your parameter must be serializable. If it isn't, then use SessionState
The entire .cs page, though I haven't done any logic here yet as I never got the parameter to work. MovieDetailsPage.xaml.cs:
public sealed partial class MovieDetailsPage
{
public MovieDetailsPage()
{
InitializeComponent();
NavigationCacheMode = Windows.UI.Xaml.Navigation.NavigationCacheMode.Enabled;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
if (e.Parameter != null)
{
string text = Convert.ToString(e.Parameter);
}
}
}
回答1:
Questioner was using Template10 (go to know about it during chat) so following is the final and updated answer for implementing Navigation.
For Template10:
way-1
using Template10.Services.SerializationService;
...
string id = (string)(sender as StackPanel).Tag;
string str=SerializationService.Json.Serialize(id);
Frame.Navigate(typeof(MovieDetailPage), str);
Way-2
var NavService = NavigationService.GetForFrame(this.Frame);
NavService.Navigate(typeof(MovieDetailPage), id);
来源:https://stackoverflow.com/questions/49848625/uwp-frame-navigate-only-crashes-when-passing-a-parameter