private void CompleteInitializePhoneApplication(object sender, NavigationEventArgs e)
{
// Set the root visual to allow the application to render
if (RootVisual != RootFrame)
//RootVisual = RootFrame;
RootVisual = new MainPage();
// Remove this handler since it is no longer needed
RootFrame.Navigated -= CompleteInitializePhoneApplication;
}
Private void button_click (Object sender, routedeventargs E)
{
Method 1: This. navigationservice. navigate (New uri ("/page1.xaml", urikind. Relative ));
Method 2: (application. Current as APP). rootframe. navigate (New uri ("/page1.xaml", urikind. Relative ));
}
The nullreferenceexception error occurs in the first method, and the navigationservice is empty. Cause:
The navigationservice attribute of page is obtained through the dependency attribute. In fact, here I want to know the characteristics of dependency attributes. Although it is maintained by a static field, there is a hash table internally to store the attribute values of different objects. In the load method of the constructor, we load the specified mainpage in the configuration file, generate its instance, and set navigationserviceproperty. Here we use mainpage as a new instance whose navigationserviceproperty is null. So of course an error will be reported here. In addition, navigationserviceproperty is an internal attribute, so we cannot set it manually. -- Excerpt
From this exception, we can find that the navigationserviceproperty attribute of the page is set after the page is loaded every time a new page is navigated. So we can use navigationservice to navigate without creating a frame. Instead, we need frame to associate page with navigationservice. Here, the new mainpage is not loaded by frame, so it cannot be navigated. -- Excerpt
The second method can be used to navigate, but the content is not displayed. You can click the back button twice in a row to launch the program. Cause:
It's easy, because the page needs to be displayed through rootvisual, and the page needs frame to be loaded for navigation. When we set the frame to rootvisual, it will be displayed. Here we set the mainpage, although frame navigation is complete, it is not displayed. However, rootvisual can only be set once, so there is no way to display it here. -- Excerpt