How to load MainPage when goBack(); form SecondPage? - windows-phone-7

I use NavigationService.Navigate("..."). But I want to load MainPage again when I click the Back button by event goBack();

In your goBack method you can use the NavigationService.GoBack() call to move from SecondPage back to the MainPage. You can view all the Navigation methods available to you on MSDN.

You can override the method OnBackKeyPress, and inside the method write code shown below, it ll navigate to MainPage.xaml
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}

If you are using binding do this:
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
App.ViewModel.LoadData();
}
And in MainViewModel.cs
public void LoadData()
{
Items.Clear();
this.Items.Add(new ItemViewModel() { LineOne = "runtime one", LineTwo = "Data info 2" });
this.IsDataLoaded = true; }

Like Nigel said, you can use NavigationService.GoBack() however this will only work if you went from the MainPage to the second page.
The only other way to do this is how you have mentioned using NavigationService.Navigate(uri).

Override the navigated to event
protected override void OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e)
{
if (PhoneApplicationService.Current.State["msg"].ToString() == "from page2")
{
// do something when its comming from page2
}
base.OnNavigatedTo(e);
}
Now that will trigger every time its navigated to but you could send some parameters so you know what to depending on what page it came from.
PhoneApplicationService.Current.State["msg"] = "from page2";
NavigationService.Navigate(new Uri("/MainPage.xaml?msg=", UriKind.Relative));

There are two ways to get back to your MainPage.
(First Method) Override the OnBackKeyPress() and write the following snippet inside it.
NavigationService.GoBack();
Note :
This will move to the MainPage only if the MainPage is the previous page in your Navigation history.
(Second Method) Override the OnBackKeyPress() and write the following snippet inside it.
NavigationService.Navigation(new Url("/MainPage.xaml",UriKind.Relative));
Note :
This will create a New MainPage and navigates to it. So if you navigated from MainPage to SecondPage and if you navigate again to MainPage using the above snippet, you will be having two MainPage in your Navigation history.
So, use any one of the snippet according to your scenario.

if WP7 or WP8 : NavigationService.GoBack()
if WP8.1 : Frame.GoBack();
and you can Override the navigated to event
protected override void
OnNavigatedTo(System.Windows.Navigation.NavigationEventArgs e) {
// do nothing }

I don't recommend overriding the OnBackKeyPress method and calling NavigationService.Navigate method within it as it may mess up your page back stack.
I assume your app has more than 2 pages. Otherwise you should just call NavigateService.GoBack() as others have recommended.
Example
Start on MainPage (backstack: empty)
Navigate to SecondPage (backstack: MainPage)
Navigate to ThirdPage (backstack: SecondPage, MainPage)
Click the back button (overridden) and you are taken to MainPage (backstack: ThirdPage, SecondPage, MainPage)
Click the back button and you are taken to the ThirdPage (backstack: SecondPage, MainPage). This is not the expected behaviour as the application should have exited.
Now you're stuck in a back button loop.
Solution
Override OnNavigatingFrom and remove any of the backstack entries you don't want the user to go to. You can either allow the user to press the back button to get back to the MainPage from the ThirdPage or you can call NavigationService.GoBack().
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
base.OnNavigatingFrom(e);
// Remove all backstack entries except for the first one
while(NavigationService.BackStack.Count() > 1)
{
NavigationService.RemoveBackEntry();
}
}

Related

I want to set an onClick listener for custom view in sketchware

{final Button tab3button2 = view findViewById(R.id.button2); View.OnClickListener() { #Override pubilc void onClick (View v)
I have tried searching for answers but all to no avail.
Just copy the code for on click on source code, and you must have a section like bindview or webview to get at the id of widget. Then just enter I'd, make sure it's different then all others on same page.
Here is what you need, I edited your code:
final Button tab3button2 = view findViewById(R.id.button2);
tab3button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View _view) {
here put the blocks that will be executed when the button gets clicked
}
});
it's recommended to add this code in the onCreate event, but if this Button is in a ListView custom view then add it in the onBindCustomView event.

Detect Back Arrow Press Of The NavigationPage in Xamarin Forms

Is there any way to detect the press of the back button of the Navigation Page in Xamarin forms?
You can override your navigation page "OnBackButtonPressed" method:
protected override bool OnBackButtonPressed()
{
Device.BeginInvokeOnMainThread(async () =>
{
if (await DisplayAlert("Exit?", "Are you sure you want to exit from this page?", "Yes", "No"))
{
base.OnBackButtonPressed();
await App.Navigation.PopAsync();
}
});
return true;
}
If you are using the shell, you can override the Shell's OnNavigating event:
void OnNavigating(object sender, ShellNavigatingEventArgs e)
{
// Cancel back navigation if data is unsaved
if (e.Source == ShellNavigationSource.Pop && !dataSaved)
{
e.Cancel();
}
}
Update:
OnBackButtonPressed event will get fired ONLY on Android when user press the Hardware back button.
Seems like you are more interested to implement when any page get disappeared you want to do something!
In that case:
You have the page's two methods -
protected override void OnAppearing()
{
base.OnAppearing();
Console.WriteLine("Hey, Im coming to your screen");
}
protected override void OnDisappearing()
{
base.OnDisappearing();
Console.WriteLine("Hey, Im going from your screen");
}
You can override those 2 methods on any page to track when they appear and disappear.
Recent updates to Xamarin forms mean you can now do this in an application made with Shell Navigation for navigation back arrow on both platforms.
Use the Shell.SetBackButtonBehavior method, for example running this code in the constructor of your page object will allow the back navigation to take place only when the bound viewmodel is not busy:
Shell.SetBackButtonBehavior(this, new BackButtonBehavior
{
Command = new Command(async() =>
{
if (ViewModel.IsNotBusy)
{
await Shell.Current.Navigation.PopAsync();
}
})
});
In the body of the Command you can do whatever you need to do when you are intercepting the click of the back button.
Note that this will affect only the navigation back button, not the Android hardware back button - that will need handling separately as per the answers above. You could write a shared method called from both the back button pressed override and the command on shell back button behaviour places to share the logic.
You must override native navigationbar button behavior with custom renderer. OnBackButtonPressed triggers only physical device button. You can read good article how to achive this here

How to override the functionality of Back button when using Navigation Controller in Xamarin.ios?

I'm working on Xamarin.iOS.When i move from one view controller to another a navigation bar is added to the view on which i just moved and a back button appears. On clicking the back button it returns me to the parent view. But i want some different functionality rather than returning to the parent view.
Can anyone help me out!
This can be accomplished by creating a custom button, and then setting that button as the back button for the view controller, such as:
public override void ViewDidLoad()
{
base.ViewDidLoad();
// Perform any additional setup after loading the view, typically from a nib.
UIBarButtonItem backButton = new UIBarButtonItem("title", UIBarButtonItemStyle.Bordered, handleBack);
this.NavigationItem.LeftBarButtonItem = backButton;
}
public void handleBack(object sender, EventArgs e)
{
Console.WriteLine("back!");
}
I hope this helps!

Xamarin.Forms removing a page

When my app first starts up I have it display a login page. In the login button if they are able to login I want to then remove the login page and navigate to a tabbed page. In this tabbed page I'll have a settings page that would allow me to get back to the login page if needed. Right now I have the following but it doesn't work. The HomePage is shown but the back arrow to the login page shows up and I don't want that.
public class LoginPage: ContentPage
{
public LoginPage() { // create controls here }
public btnLogin_Clicked(object sender, EventArgs e){
Navigation.PopAsync(); // remove this page (doesn't work)
Navigation.PushAsync(new HomePage());
}
}
public class App : Application
{
public App()
{
MainPage = new NavigationPage(new LoginPage());
}
}
Xamarin.Forms 1.3 added the capability to add and remove pages resetting the root of the navigation stack as you suggest. Your code indicates that you are using at least version 1.3. However, calling PopAsync() right off the bat is not the method you want to use as it will not pop off a page if it is the only page in the stack. Instead use the INavigation interface's InsertPageBefore(newPage, pageToPutBefore) method first and then pop the login page off the end of the stack.
You can try code similar to this:
public async void btnLogin_Clicked(object sender, EventArgs e)
{
// Do some login logic and if successful ...
Navigation.InsertPageBefore(new HomePage(), this);
await Navigation.PopAsync().ConfigureAwait(false);
}
There are several new methods in Xamarin.Forms 1.3 that substantially improve the navigation capabilities. Another possible solution to the above problem would be to first add the HomePage to the end of the stack and then use the new RemovePage method to remove the login page from the start of the stack leaving the HomePage as the only page left. One thing you want to be careful of, if you are adding the new page using an asynchronous method like PushAsync you will need to await to call to ensure the new page is finished being added to the stack before removing the old page.
Yet another solution: Change MainPage property
in App.cs Constructor:
public App()
{
MainPage = new LoginPage();
}
in your Login method:
Device.BeginInvokeOnMainThread(() =>
{
Application.Current.MainPage = new NavigationPage(new HomePage());
});
For your second point , the back arrow to the login page shows up and you don't want that >>
Use this NavigationPage.SetHasBackButton(YourPage, false);
This will remove the Back Button from your navigation bar
As an example for your code above,
HomePage myHomePage = new HomePage();
NavigationPage.SetHasNavigationBar(myHomePage , false);
Navigation.PushAsync(myHomePage);
You can explore more methods of NavigationPage - such as SetHasNavigationBar and many more, they are really good.
Please let me know if this helps.

Windows Phone back button to terminate the app

I have a main page with some options. One of them is to navigate to page 1 where there are two arrows. One that navigates to page2, page3, and the other arrow page3, page2, page1 like a loop. There is also an arrow that navigates to main page.
I want to ask if there is a way when the user presses the back button to terminate the app from whatever page the user is currently at and not to navigate through all pages.
edit
if i want when i press the back to always navigate to the mainpage what i have to do ?
clear the back stack inside the onbackkeypress function where you want to exit the app. And it will exit the app normally.
[Updated]
1) after clearing back stack. Use NavigationService.Navigate(new Uri("MainPage.xaml",UriKind.Relative)); to traverse to mainpage and do e.Cancel = true in the next statement.
2) Or clear the back stack upto the mainpage. and automatically the back press will take you to the mainpage. inside the mainpage clear the back stack fully inside the OnNavigatedTo function so that the first item is always your mainpage and user can exit easily.
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
while (NavigationService.CanGoBack)
NavigationService.RemoveBackEntry();
e.Cancel = true;
return;
}
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
while (NavigationService.CanGoBack)
NavigationService.RemoveBackEntry();
}
Throw an exception in OnBackKeyPress which terminates the app.
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
throw an exception();
}
You can also do like this,
check
e.NavigationMode == System.Windows.Navigation.NavigationMode.Back
in OnNavigatedTo event (you need to override this every page) and call
NavigationService.GoBack();
there is no direct way of exiting an app.. see here
hope this will work. If its XNA
if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
this.Exit();

Resources