【发布时间】:2016-02-07 21:32:51
【问题描述】:
我曾经在 Windows Phone 8.1 XAML 中使用硬件按钮 API。但是,在 UWP 中,某些设备没有返回按钮。如何适应新的应用模型?
【问题讨论】:
标签: windows-10 windows-10-mobile
我曾经在 Windows Phone 8.1 XAML 中使用硬件按钮 API。但是,在 UWP 中,某些设备没有返回按钮。如何适应新的应用模型?
【问题讨论】:
标签: windows-10 windows-10-mobile
一点解释的答案。
您可以使用 SystemNavigationManager 的 Windows.UI.Core 命名空间
如果您只想处理单页导航。请按照以下步骤操作
第 1 步。使用命名空间Windows.UI.Core
using Windows.UI.Core;
第 2 步。 为当前视图注册返回请求事件。最好的地方是InitializeComponent()之后的类的主要构造函数。
public MainPage()
{
this.InitializeComponent();
//register back request event for current view
SystemNavigationManager.GetForCurrentView().BackRequested += MainPage_BackRequested;
}
第 3 步。 处理 BackRequested 事件
private void Food_BackRequested(object sender, BackRequestedEventArgs e)
{
if (Frame.CanGoBack)
{
Frame.GoBack();
e.Handled = true;
}
}
rootFrame在一个地方完成申请
处理所有视图的所有后退按钮的最佳位置是App.xaml.cs
第 1 步。使用命名空间Windows.UI.Core
using Windows.UI.Core;
第 2 步。 为当前视图注册返回请求事件。最好的地方是OnLaunched,就在Window.Current.Activate之前
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
...
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
Window.Current.Activate();
}
第 3 步。 处理 BackRequested 事件
private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (rootFrame.CanGoBack)
{
rootFrame.GoBack();
e.Handled = true;
}
}
参考资料-Handle back button pressed in UWP
希望这对某人有帮助!
【讨论】:
上面的代码是完全正确的,但你必须在 rootFrame 变量中添加框架对象。下面给出:
private Frame _rootFrame;
protected override void OnLaunched(LaunchActivatedEventArgs e)
{
Frame rootFrame = Window.Current.Content as Frame;
if (Window.Current.Content==null)
{
_rootFrame = new Frame();
}
}
并将这个 _rootFrame 传递给 OnBackRequested 方法。喜欢:
private void OnBackRequested(object sender, BackRequestedEventArgs
{
if (_rootFrame.CanGoBack)
{
_rootFrame.GoBack();
e.Handled = true;
}
}
【讨论】:
您可以使用 BackRequested 事件来处理返回请求:
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
if (App.MasterFrame.CanGoBack)
{
rootFrame.GoBack();
e.Handled = true;
}
【讨论】:
SystemNavigationManager在哪里?我找不到它。
Windows.UI.Core 命名空间中。 VS 应该建议你这样做。