如何拦截Xamarin表单中单击的导航栏后退按钮? [英] How to intercept Navigation Bar Back Button Clicked in Xamarin Forms?
问题描述
我有一个xamarin表单页面,用户可以在其中更新表单中的某些数据.我需要截取单击的导航栏后退按钮,以警告用户是否尚未保存某些数据.该怎么办?
I have a xamarin form page where a user can update some data in a form. I need to intercept the Navigation Bar Back Button Clicked to warn the user if some data have not been saved.How to do it?
我能够使用Android.MainActivity.OnBackPressed()
截获Android中单击的硬件后退"按钮,但是该事件仅在硬件后退"按钮单击时引发,而不会在导航"后退按钮单击时引发.
I'm able to intercept the hardware Bar Back Button Clicked in Android using the Android.MainActivity.OnBackPressed()
, but that event is raised only on hardware Bar Back Button Clicked, not on Navigation Bar Back Button Clicked.
我也尝试覆盖Xamarin.Forms.NavigationPageOnBackButtonPressed()
,但是它不起作用.为什么?
有人已经解决了这个问题吗?
I tried also to override Xamarin.Forms.NavigationPageOnBackButtonPressed()
but it doesn't work. Why?
Any one have already solved that issue?
我也尝试通过覆盖OnDisappear()
来解决两个问题:
I also tried by overriding OnDisappear()
, there are two problems:
- 该页面已经在视觉上消失了,因此您确定吗?"对话框出现在上一页上.
- 无法取消后退动作.
那么,有可能拦截导航栏的后退按钮按下吗?
So, is it possible to intercept the navigation bar back button press?
推荐答案
我能够显示一个确认对话框,该对话框可以通过重写FormsApplicationActivity中的以下方法来取消导航.
I was able to show a confirmation dialog that could cancel navigation by overriding the following methods in the FormsApplicationActivity.
// navigation back button
public override bool OnOptionsItemSelected(IMenuItem item)
{
if (item.ItemId == 16908332)
{
var currentViewModel = (IViewModel)navigator.CurrentPage.BindingContext;
currentViewModel.CanNavigateFromAsync().ContinueWith(t =>
{
if (t.Result)
{
navigator.PopAsync();
}
}, TaskScheduler.FromCurrentSynchronizationContext());
return false;
}
else
{
return base.OnOptionsItemSelected(item);
}
}
// hardware back button
public async override void OnBackPressed()
{
var currentViewModel = (IViewModel)navigator.CurrentPage.BindingContext;
// could display a confirmation dialog (ex: "Cancel changes?")
var canNavigate = await currentViewModel.CanNavigateFromAsync();
if (canNavigate)
{
base.OnBackPressed();
}
}
navigator.CurrentPage是INavigation服务的包装.我不必从模式页面取消导航,因此我只处理NavigationStack.
The navigator.CurrentPage is a wrapper around the INavigation service. I do not have to cancel navigation from modal pages so I am only handling the NavigationStack.
this.navigation.NavigationStack[this.navigation.NavigationStack.Count - 1];
这篇关于如何拦截Xamarin表单中单击的导航栏后退按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!