Windows Phone 8 NavigationService.Navigate throws a NullReferenceException - c#

I am working on a C# Project for WindowsPhone 8. When the user deactivates the App (i.e. Going to the main menu) I stop some timers and save some things. This works fine.
But when the user reactivates the app I want to navigate the user to a pause screen.
NavigationService.Navigate(new Uri("/Pause.xaml", UriKind.Relative));
The Code is simple and works perfect when the app isn't deactivated. But when the user reactivates the app it throws a NullReferenceException.
I already tried several things such as:
public void pause_for_activated()
{
this.Loaded += navigate_pause();
}
private RoutedEventHandler navigate_pause()
{
NavigationService.Navigate(new Uri("/Pause.xaml", UriKind.Relative));
return navigate_pause();
}
When I start the app without automatically navigating to the pause screen and then press a button to navigate it works.
My Question is now when can I automatically navigate and how can I do this ?
In advance , I thank you already.

I got no answer until now, but I found a solution for me so I decided to put it here.
Loaded += navigate_pause();
private RoutedEventHandler navigate_pause()
{
Dispatcher.BeginInvoke(() =>
{
((PhoneApplicationFrame)Application.Current.RootVisual).Navigate(new Uri("/Pause.xaml", UriKind.Relative));
});
return null;
}

Related

Clear the navigation history of WebView in WinRT Windows Store App C#

Scenario
I am creating a simple embedded "browser" for my app, which opens in a Popup, when the user clicks on a button with a hyperlink designed to open "in-app".
The popup is opened, and the (simply-named) WebView is navigated to the URL specified in the hyperlink.
There are the typical Back, Forward and Refresh/Stop buttons that are enabled/disabled accordingly.
Current Situation
I have wired up the necessary events for NavigationStarted, NavigationCompleted and others for Falied, Loaded etc. etc.
These are performed along with some "naughty" ViewModel wiring when the UserControl is loaded TL;DR - there is no way I can find to keep to MVVM practice with WebViews, what a PITA!:
private void OnLoaded(object sender, RoutedEventArgs e)
{
if (this.DataContext is IWebViewUserControlViewModel)
{
this.WebView.ContentLoading += OnWebViewContentLoading;
this.WebView.DOMContentLoaded += OnWebViewDomContentLoaded;
this.WebView.NavigationStarting += OnWebViewNavigationStarting;
this.WebView.NavigationCompleted += OnWebViewNavigationCompleted;
this.WebView.UnviewableContentIdentified += OnWebViewUnviewableContentIdentified;
this.WebView.NavigationFailed += OnWebViewNavigationFailed;
this.viewModel = DataContext as IWebViewUserControlViewModel;
NavigateToUrl(this.viewModel?.Url);
}
}
This is so that I navigate to the URL when the UserControl is loaded, and can evaluate the button states as the user navigates around using the events above.
The NavigateToUrl() method just contains a try/catch block to counteract any errors forming the Uri etc.:
private void NavigateToUrl(string url)
{
try
{
var uri = new Uri(url);
this.WebView.Navigate(uri);
}
catch (Exception ex)
{
this.WebView.NavigateToString($"An error occurred: {ex.Message}")
}
}
Back/Forward UX
In particular the Back and Forward buttons are disabled/enabled when navigation to a page is started/completed respectively.
I evaluate their IsEnabled states like so:
btnBackButton.IsEnabled = this.WebView.CanGoBack;
btnForwardButton.IsEnabled = this.WebView.CanGoForward;
This works fine throughout the entire time that the user is browsing.
The Issue
Should the user close the popup, and re-open it via the same or a different link, the correct URL is navigated to - all good.
The issue is, that their previous browsing session was never cleared from the MyWebView, and thus the btnBackButton (not the forward, as this the latest navigation in the history stack) is now enabled again - allowing them to traverse their previously visited pages.
I don't want this behaviour.
I would like it to appear that their session is a "new", fresh one - without the Back button enabled - as if it had just been opened.
What I have already tried...
I am unable to manually set the MyWebView.CanGoBack/MyWebView.CanGoForward properties to false when the popup is (re)opened.
They are get-only properties, so this is not possible.
I have tried re-initializing the WebView control when the containing UserControl is Loaded (in the same OnLoaded delegate as above):
private void OnLoaded(object sender, RoutedEventArgs e)
{
if (this.DataContext is IWebViewUserControlViewModel)
{
// Re-initialize the WebView
this.WebView = new WebView();
// Detect when the new control has loaded, and then wire up events/navigate as normal
this.WebView.Loaded += (sender, e) =>
{
this.WebView.ContentLoading += OnWebViewContentLoading;
this.WebView.DOMContentLoaded += OnWebViewDomContentLoaded;
this.WebView.NavigationStarting += OnWebViewNavigationStarting;
this.WebView.NavigationCompleted += OnWebViewNavigationCompleted;
this.WebView.UnviewableContentIdentified += OnWebViewUnviewableContentIdentified;
this.WebView.NavigationFailed += OnWebViewNavigationFailed;
this.viewModel = DataContext as IWebViewUserControlViewModel;
NavigateToUrl(this.viewModel?.Url);
}
}
}
In the hope that this might work - but the Loaded delegate of the WebView is never fired.
In the UI, the WebView just doesn't appear.
Help!?
Is there any way for me to clear the navigation history for the WebView control, so it appears that the browsing session is a "new" one?
Your help is appreciated, as always. Many thanks.
If your app is Windows 8.1, actually there is no programmatic way to clear the webview cache according to what #Matt said in this link(part 7).
And if it is a UWP app, please refer to this doc.

Windows phone 8.1 BackButton Navigation issue

I am developing Windows phone 8.1 Silver Light Application. In the application there are so many screens. Pages are navigating perfectly.
My issue is when i press on back button(Windows Phone Back Button) The pages are going back to the previous pages. I want to stop back button navigation in my application. I followed below link but i am not succeeded.
https://social.msdn.microsoft.com/Forums/windowsapps/en-us/131a99ce-53a4-4389-81e9-7801af57b78b/used-hardwarebuttonsbackpressed-handler
Could any one advise me.
Try this for back button on your XAML.cs page :
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
base.OnBackKeyPress(e);
if (NavigationService.CanGoBack)
{
while (NavigationService.RemoveBackEntry() != null)
{
NavigationService.RemoveBackEntry();
}
}
}

Override BackKeyPress in a classlibrary, is that possible on WP8?

I pass a PhoneApplicationPage instance to a classlibrary, and popup an usercontrol in this classlibrary, when I press back button, the whole application exit. Yesterday I sovled the problem in an application, but I cannot use the method in this classlibrary case.
I tried to subscribe to the event(BackKeyPress), but VS2012 says "parent_BackKeyPress" "System.EventHandler" override and delegate cannot match. I checked, they match.
PhoneApplicationPage mContext=...;
mContext.BackKeyPress += new EventHandler(parent_BackKeyPress);
void parent_BackKeyPress(CancelEventArgs e)
{
ppChangePIN.IsOpen = false;
Application.Current.RootVisual.Visibility = Visibility.Visible;
}
anything incorrect here? plus, can I use navigationservice in classlibrary? I did this before to navigate to a page created in the classlibrary like below, well it ends up crashing. Some say can't use pages in classlibrary, instead we should use Popup(usercontrol).
mContext.NavigationService.Navigate(new Uri("/ChangePINPage.xaml", UriKind.Relative));
I have successfully done just that:
// or some other method of accessing the current page
// - but via Application, to which you have access also in class library
var currentPage = (PhoneApplicationPage)((PhoneApplicationFrame)Application.Current.RootVisual).Content;
currentPage.BackKeyPress += (sender, args) =>
{
// Display dialog or something, and when you decide not to perform back navigation:
args.Cancel = true;
};
Of course you have to make sure that this code is executed if and only if the CurrentPage is the main page.
I also use Pages in class library. You can use NavigationService in class library: you can get it for example from current page obtained as above (currentPage.NavigationService). Or you could use the Navigate method of PhoneApplicationFrame:
((PhoneApplicationFrame)Application.Current.RootVisual)
.Navigate(
new Uri(
"/ClassLibraryName;component/SamplePage.xaml",
UriKind.Relative));
As the short Uris like "/SamplePage.xaml" will work in Application Project, to navigate to page in class library you have to give full location: "/ClassLibraryName;component/SamplePage.xaml".
But note, that if the application chooses to display message box to stop from exiting, it will not pass certification, as (from Technical certification requirements for Windows Phone):
5.2.4.2 – Back button: first screen
Pressing the Back button from the first screen of an app must close the app.

Kill an app when return from WebBrowseTask

I made a small app, and I have a button than pin to start a web blog via a xaml, so when the tile is pin, it goes to the xaml, which automatically redirect to the blog by WebBrowserTask. MY problem is that if they press the back button from the web page, they go to the xaml, and I want them to go directly to the start menu, so I'm looking for a way to kill the app when they return from the
the xaml code is
private void WebPages_Loaded(object sender, RoutedEventArgs e)
{
try
{
WebBrowserTask task = new WebBrowserTask();
task.Uri = new Uri(NavigationContext.QueryString["uri"]);
task.Show();
}
catch (KeyNotFoundException)
{
MessageBox.Show("No URI was passed to the app.");
}
}
I don't know if this is possible, but if someone knows i'll be pleased. Thanks
Try this : Windows Phone 7 close application to kill an app, you may want to try this solution :
if (NavigationService.CanGoBack)
{
while (NavigationService.RemoveBackEntry() != null)
{
NavigationService.RemoveBackEntry();
}
}
You may want to load your blog inside a WebBrowser control rather than running a WebBrowseTask. Then, clear the back stack if need be in the OnBackKeyPress event. If you open a WebBrowserTask, the user will have to hit back to resume your app and then hit back again to return to the start menu. You won't be able to exit your app automatically after resuming. Its against the marketplace guidelines.

Decide which page to go when launching in Windows Phone 7.1 app

I am building an app for Windows Phone 7.1 using c#.
when the app is opening, if the user is the first time using it, then go to the "set up a password" page, else go to the "login page".
I wanted to use NavigationService.Navigate(Uri), but I don't know where should i call this function?
I suggest to save the password to some sort of (encrypted) persistent storage, and try to retrieve it when the app starts.
Then add this code in the App.xaml and it should do the trick
void RootFrame_Navigating(object sender, NavigatingCancelEventArgs e)
{
// Only care about MainPage
if (e.Uri.ToString().Contains("/MainPage.xaml") != true)
return;
var password = GetPasswordFromSomePersistentStorage();
// Cancel current navigation and schedule the real navigation for the next tick
// (we can't navigate immediately as that will fail; no overlapping navigations
// are allowed)
e.Cancel = true;
RootFrame.Dispatcher.BeginInvoke(delegate
{
if (string.IsNullOrWhiteSpace(password))
RootFrame.Navigate(new Uri("/InputPassword.xaml", UriKind.Relative));
else
RootFrame.Navigate(new Uri("/ApplicationHome.xaml", UriKind.Relative));
});
}
Make sure you have added the handler on the App() constructor
RootFrame.Navigating += new NavigatingCancelEventHandler(RootFrame_Navigating);
And also, the MainPage.xaml, is just and empty page (set it up as you begin page) that will be used to catch the initial navigation event.
Hope its helps.

Categories