Xamarin窗体阻止用户后退键
在我的Xamarin表单应用程序中,当用户单击主页上的后退按钮时,我希望显示一条确认消息。有没有办法做到这一点? 我在主页中重写了OnBackButtonPressed方法。但当按back键时,应用程序仍将关闭。这是我的密码Xamarin窗体阻止用户后退键,xamarin,xamarin.ios,xamarin.android,xamarin.forms,Xamarin,Xamarin.ios,Xamarin.android,Xamarin.forms,在我的Xamarin表单应用程序中,当用户单击主页上的后退按钮时,我希望显示一条确认消息。有没有办法做到这一点? 我在主页中重写了OnBackButtonPressed方法。但当按back键时,应用程序仍将关闭。这是我的密码 protected override bool OnBackButtonPressed () { //return base.OnBackButtonPressed (); return false; } 您可以覆盖任何Xa
protected override bool OnBackButtonPressed ()
{
//return base.OnBackButtonPressed ();
return false;
}
您可以覆盖任何Xamarin.Form页面的OnBackButtonPressed。但它只适用于Android和Windows Phone设备中的物理按钮
protected override bool OnBackButtonPressed () {
DisplayAlert("title","message","ok");
return true;
}
对于虚拟渲染器,您需要创建CustomRenders并拦截click处理程序。在iOS中,这可能很棘手,因为用户可以回去做其他动作(例如刷卡手势)。一旦你截获它,你只需要创建你的确认消息(我假设你知道怎么做)
对于iOS,您可以执行以下操作:
[assembly: ExportRenderer (typeof (YourPage), typeof (YourPageRenderer))]
namespace YourNamespace {
public class YourPageRenderer : PageRenderer {
public override void ViewWillAppear (bool animated) {
base.ViewWillAppear (animated);
Action goBack = () => page.DisplayAlert("title","message","ok");
var backButton = new NavBackButton (goBack);
navigationItem.LeftBarButtonItem = new UIBarButtonItem (backButton);
}
}
public class NavBackButton : UIView {
public NavBackButton (Action onButtonPressed) {
SetButton (onButtonPressed);
}
UILabel text;
UIImageView arrow;
void SetButton(Action onButtonPressed){
arrow = new UIImageView(new CGRect(-25,0, 50, 50)) {
Image = new UIImage("Images/back").ImageWithRenderingMode(UIImageRenderingMode.AlwaysTemplate)
};
arrow.TintColor = Colors.DarkGreen.ToUIColor ();
text = new UILabel(new CGRect(arrow.Frame.Width + arrow.Frame.X -15, arrow.Frame.Height /2 - 10, 40, 20)) { Text = "Back" };
text.TextColor = Colors.DarkGreen.ToUIColor ();
Frame = new CGRect(0,0,text.Frame.Size.Width + arrow.Frame.Width, arrow.Frame.Height);
AddSubviews (new UIView[] { arrow, text });
var tapGesture = new UITapGestureRecognizer (onButtonPressed);
AddGestureRecognizer (tapGesture);
}
public override void TouchesBegan (Foundation.NSSet touches, UIEvent evt) {
base.TouchesBegan (touches, evt);
text.TextColor = UIColor.YourColor;
arrow.TintColor = UIColor.YourColor;
}
public override void TouchesEnded (Foundation.NSSet touches, UIEvent evt){
base.TouchesEnded (touches, evt);
arrow.TintColor = UIColor.YourColor;
text.TextColor = UIColor.YourColor;
}
}
}
PS您需要提供一个箭头图像(“Images/back”)I wnat以等待方法DisplayAlert(标题,消息,“Yes”,“No”)获得结果。但是在overided方法中无法做到这一点您可以做到,但是您需要将被重写的方法标记为async。请注意,DisplayAlert只返回任务,而不返回任务。如果你想更深入地了解这一点,请问另一个问题,如果这个答案对你有用,请标记为正确。