在类库中覆盖BackKeyPress,在WP8上是可能的

本文关键字:类库 覆盖 BackKeyPress WP8 | 更新日期: 2023-09-27 18:33:46

我将一个PhoneApplicationPage实例传递给一个类库,并在这个类库中弹出一个用户控件,当我按下后退按钮时,整个应用程序退出。昨天我在应用程序中解决了这个问题,但我不能在类库的情况下使用该方法。我尝试订阅事件(BackKeyPress(,但VS2012显示"parent_BackKeyPress"System.EventHandler"覆盖和委托无法匹配。我检查了一下,它们匹配。

PhoneApplicationPage mContext=...;mContext.BackKeyPress += new EventHandler(parent_BackKeyPress(;void parent_BackKeyPress(CancelEventArgs e( { ppChangePIN.IsOpen = false; Application.Current.RootVisual.Visibility = Visibility.Visible; }

这里有什么不对的地方吗? 另外,我可以在类库中使用导航服务吗? 我之前这样做是为了导航到在类库中创建的页面,如下所示,它最终崩溃了。有人说不能使用类库中的页面,我们应该使用Popup(usercontrol(。 mContext.NavigationService.Navigate(new Uri("/ChangePINPage.xaml", UriKind.Relative((;

在类库中覆盖BackKeyPress,在WP8上是可能的

我已经成功地做到了这一点:

// or some other method of accessing the current page
// - but via Application, to which you have access also in class library
var currentPage = (PhoneApplicationPage)((PhoneApplicationFrame)Application.Current.RootVisual).Content;
currentPage.BackKeyPress += (sender, args) =>
    {
        // Display dialog or something, and when you decide not to perform back navigation:
        args.Cancel = true;
    };

当然,您必须确保当且仅当当前页面是主页时执行此代码。

我还在类库中使用页面。您可以在类库中使用导航服务:例如,您可以从上述(currentPage.NavigationService(获得的当前页面中获取它。或者你可以使用 PhoneApplicationFrame 的 Navigate 方法:

((PhoneApplicationFrame)Application.Current.RootVisual)
    .Navigate(
        new Uri(
            "/ClassLibraryName;component/SamplePage.xaml", 
            UriKind.Relative));
由于像"/SamplePage.xaml

"这样的短 Uri 将在应用程序项目中工作,因此要导航到类库中的页面,您必须提供完整的位置:"/ClassLibraryName;component/SamplePage.xaml"。

但请注意,如果应用程序选择显示消息框以停止退出,则它将无法通过认证,因为(来自 Windows Phone 的技术认证要求(:

5.2.4.2 – 后退按钮:第一个屏幕

从应用的第一个屏幕按"后退"按钮必须关闭该应用。