首页 > 解决方案 > 在 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 后退功能?

标签: c#xamarinxamarin.formsuwp

解决方案


找到了一个渲染器解决方法,允许您处理后退按钮:

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() 以完全禁用它)。


推荐阅读