有点卡在这里。我有一个splitview应用程序,当按下反键键驻留在Appx.cs中时,该应用程序具有向后导航的事件。
我想在splitviews内容页面中导航的其中一个页面中定义一个不同的操作(例如,当某个元素可见以解除该元素时),但应用程序始终遵循appx.cs中设置的事件,并且忽略内容框架中加载的页面中的事件。这是appx.cs中的代码:
protected async override void OnLaunched(LaunchActivatedEventArgs e)
{
// Do not repeat app initialization when the Window already has content,
// just ensure that the window is active
if (Window.Current.Content == null)
{
// Create a Frame to act as the navigation context and navigate to the first page
_rootFrame = new Frame();
_rootFrame.NavigationFailed += OnNavigationFailed;
_rootFrame.Navigated += OnNavigated;
if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
{
//TODO: Load state from previously suspended application
}
// Place the frame in the current Window
Window.Current.Content = new MainPage(_rootFrame);
// Register a handler for BackRequested events and set the
// visibility of the Back button
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
SystemNavigationManager.GetForCurrentView().AppViewBackButtonVisibility =
_rootFrame.CanGoBack ?
AppViewBackButtonVisibility.Visible :
AppViewBackButtonVisibility.Collapsed;
}
}
private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
if (_rootFrame != null && _rootFrame.CanGoBack)
{
e.Handled = true;
_rootFrame.GoBack();
}
}
以下是加载到splitviews内容窗格的其中一个页面中的代码:
public CalcOutputPage()
{
this.InitializeComponent();
// add page specific handling of back navigation when entering this page
SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;
}
// page specific back button navigation
private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
if (MobileStackPanel.Visibility == Visibility.Visible)
{
MobileStackPanel.Visibility = Visibility.Collapsed;
e.Handled = true;
}
else
{
e.Handled = false;
}
}
但这不起作用。如果第一页加载到导航堆栈中,它可以工作,但在其他所有时间,该应用程序都遵循appx.cs中的导航说明
所以澄清一下:
任何帮助将不胜感激。我试图让这个工作失去理智:P
答案 0 :(得分:7)
事件处理程序按照添加的顺序触发,因此这方面没有运气。另一种方法是制作自己的活动,包装原始活动。在App.xaml.cs
:
public event EventHandler<BackRequestedEventArgs> BackRequested;
private void OnBackRequested(object sender, BackRequestedEventArgs e)
{
// Raise child event
var eventHandler = this.BackRequested;
if (eventHandler != null)
{
eventHandler(sender, e);
}
if (!e.Handled)
{
if (_rootFrame != null && _rootFrame.CanGoBack)
{
e.Handled = true;
_rootFrame.GoBack();
}
}
}
然后在您的页面中,订阅子事件而不是主事件:
((App)(App.Current)).BackRequested += OnBackRequested;
确保在离开页面时取消订阅该事件,否则可能会导致内存泄漏。