代码之家  ›  专栏  ›  技术社区  ›  David_001

如何处理WindowsPhone7上的后退按钮

  •  43
  • David_001  · 技术社区  · 16 年前

    在WindowsPhone7模拟器上,当按下“硬件后退”按钮时,默认行为是关闭当前应用程序。我想重写此默认行为,以便它导航到应用程序中的上一页。

    经过一些研究,似乎可以通过覆盖OnBackKeyPress方法来实现这一点,如下所示:

    protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
    {
        // do some stuff ...
    
        // cancel the navigation
        e.Cancel = true;
    }
    

    但是,单击后退按钮仍然会关闭我的应用程序。在上面的方法上放置一个断点表明它从未被调用。我的应用程序退出代码上有另一个断点,这个断点 击中。

    3 回复  |  直到 16 年前
        1
  •  29
  •   David_001    16 年前

    Navigate 方法在应用程序中的页面之间移动。

    我以前的导航方法是更改根视觉,如:

    App.Current.RootVisual = new MyPage(); 
    

    这意味着我可以将所有页面都保存在内存中,这样就不需要缓存存储在页面上的数据(有些数据是通过网络收集的)。

    现在似乎我需要在页面框架上实际使用Navigate方法,它为我要导航的页面创建一个新实例。

    (App.Current.RootVisual as PhoneApplicationFrame).Navigate(
                                        new Uri("/MyPage.xaml", UriKind.Relative)); 
    

        2
  •  23
  •   ManicBlowfish    15 年前

    如果不需要默认的back键行为,请在OnBackKeyPress的CancelEventArgs参数中设置Cancel=true。在我的页面中,我已重写“后退”按钮以关闭web浏览器控件,而不是导航到后退。

        protected override void OnBackKeyPress(CancelEventArgs e)
        {
            if (Browser.Visibility == Visibility.Visible)
            {
                Browser.Visibility = Visibility.Collapsed;
                e.Cancel = true;
            }
        }
    
        3
  •  3
  •   Stonetip    15 年前

    <ObjectAnimationUsingKeyFrames Storyboard.TargetName="ControlScroller" Storyboard.TargetProperty="(UIElement.Visibility)">
    <ObjectAnimationUsingKeyFrames.KeyFrames>
        <DiscreteObjectKeyFrame KeyTime="00:00:00">
            <DiscreteObjectKeyFrame.Value>
                <Visibility>Visible</Visibility>
            </DiscreteObjectKeyFrame.Value>
        </DiscreteObjectKeyFrame>
    </ObjectAnimationUsingKeyFrames.KeyFrames>
    

    然后在页面的代码中:

    protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
    {
    
        if(ControlScroller.Visibility == Visibility.Visible  && StoryboardHideControlSlider.GetCurrentState() != ClockState.Active)
        {
            StoryboardHideControlSlider.Begin();
    
            ContentGrid.IsHitTestVisible = true;
    
            e.Cancel = true;
        }
    }
    

    注意:在隐藏ContentScroller(这是一个网格)的序列图像板中,KeyTime设置为“00:00:01”,因为我希望它在滑动(和淡出)视图时保持可见。

    注2:原因 StoryboardHideControlSlider.GetCurrentState() != ClockState.Active

    推荐文章