c# - 在 Xamarin.Forms UWP 应用程序中拦截鼠标后退按钮
问题描述
我一直在尝试拦截从我的 Xamarin.Forms UWP 应用程序中的页面返回的用户,以便阻止它或向他们显示“你确定吗?” 对话。
我已经能够在 ContentPage 的构造函数中使用它删除导航栏后退按钮:
NavigationPage.SetHasBackButton(this, false);
但是,鼠标 (XButton1) 上的后退按钮仍会导致页面后退。我尝试在页面上使用它禁用它:
protected override bool OnBackButtonPressed()
{
return true;
}
这将禁用 Android 之类的硬件后退按钮,但在点击鼠标后退按钮时根本不会调用它。我还尝试过在 UWP MainPage 上使用 PointerPressed 事件:
public MainPage()
{
this.InitializeComponent();
LoadApplication(new MyApp.App());
this.PointerPressed += MainPage_PointerPressed;
}
private void MainPage_PointerPressed(object sender, PointerRoutedEventArgs e)
{
PointerPoint currentPoint = e.GetCurrentPoint(this);
if (currentPoint.PointerDevice.PointerDeviceType == PointerDeviceType.Mouse)
{
PointerPointProperties pointerProperties = currentPoint.Properties;
if (pointerProperties.IsXButton1Pressed)
{
// back button pressed
}
}
}
如果应用程序的当前页面当前位于 NavigationPage 中,则除XButton1 鼠标后退按钮之外的所有鼠标输入都会正确调用此方法- 几乎就像 Xamarin.Forms 在沿途某处拦截它一样。在导航页面之外,它会很好地拾取 XButton1,并且它总是会拾取所有其他输入(包括 XButton2)。
有没有办法拦截或禁用 Xamarin.Forms UWP 应用的 XButton1 后退功能?
解决方案
找到了一个渲染器解决方法,允许您处理后退按钮:
using Xamarin.Forms.Platform.UWP;
using Windows.UI.Xaml.Input;
using Windows.Devices.Input;
[assembly: ExportRenderer(typeof(Xamarin.Forms.Page), typeof(MyApp.UWP.Renderers.PageCustomRenderer))]
namespace MyApp.UWP.Renderers
{
public class PageCustomRenderer : PageRenderer
{
protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.Page> e)
{
base.OnElementChanged(e);
this.PointerPressed += PageCustomRenderer_PointerPressed;
}
private void PageCustomRenderer_PointerPressed(object sender, PointerRoutedEventArgs e)
{
if (e.Handled) return;
var point = e.GetCurrentPoint(Control);
if (point == null || point.PointerDevice.PointerDeviceType != PointerDeviceType.Mouse) return;
if (point.Properties.IsXButton1Pressed)
{
e.Handled = true;
if (Element != null)
{
Element.SendBackButtonPressed();
}
}
}
}
}
然后,您可以像在 OP 中一样覆盖页面上的 OnBackButtonPressed 以停止它(或从上面的渲染器中删除 Element.SendBackButtonPressed() 以完全禁用它)。
推荐阅读
- vb.net - 有没有办法在 C1FlexGrid 中的各个列上设置最小宽度?
- unity3d - 如何统一制作逼真的平面运动
- reactjs - 如何将焦点设置在组件 html 标记上
- javascript - Vuetify:基于选择的依赖v-select
- azure - 如何使 API 始终可访问,而不仅仅是在项目执行时访问?
- sas - 一旦多个变量满足条件,就放弃观察
- python - 使用 MongoEngine - Python Flask 从主文档中按字符串嵌入文档进行过滤
- batch-file - 执行计划任务操作的服务
- python - else 命令运行不正确?(Python 3 初学者)
- pointers - golang return []*TreeNode{} 和 return []*TreeNode{nil} 有什么区别