在下面的async onnavigationhandler中,将e.Cancel恢复为false应该允许用户从当前页面导航出去。不知怎的,导航意外地失败了!
private async void NavigationService_OnNavigating(object sender, NavigatingCancelEventArgs e)
{
var model = DataContext as ViewModel;
if (model == null || !model.IsDirty) return;
e.Cancel = true;
var option = MessageDialogResult.Negative;
try
{
var metroWindow = (MainWindow)Application.Current.MainWindow;
option = await metroWindow.ShowMessageAsync("Form", "Quit?", MessageDialogStyle.AffirmativeAndNegative);
}
finally
{
if (option == MessageDialogResult.Affirmative)
//******Allow the user to move away********
e.Cancel = false;
}
}
有谁能解释一下这个问题吗?任何与。net线程相关的东西?更新:用决策变量_canNavigate
求解了该问题。
private bool _canNavigate = false;
private async void NavigationService_OnNavigating(object sender, NavigatingCancelEventArgs e)
{
var model = DataContext as ViewModel;
if (model == null || !model.IsDirty) return;
if (!_canNavigate)
{
e.Cancel = true;
var metroWindow = (MainWindow)Application.Current.MainWindow;
var option = await metroWindow.ShowMessageAsync("Form", "Quit?", MessageDialogStyle.AffirmativeAndNegative);
if (option == MessageDialogResult.Affirmative)
{
_canNavigate = true;
_navigationService.Navigate(e.Uri);
}
else _canNavigate = false;
}
else
{
_canNavigate = false;
}
}
这个问题已经用决策变量_canNavigate
笨拙地解决了。
private bool _canNavigate = false;
private async void NavigationService_OnNavigating(object sender, NavigatingCancelEventArgs e)
{
var model = DataContext as ViewModel;
if (model == null || !model.IsDirty) return;
if (!_canNavigate)
{
e.Cancel = true;
var metroWindow = (MainWindow)Application.Current.MainWindow;
var option = await metroWindow.ShowMessageAsync("Form", "Quit?", MessageDialogStyle.AffirmativeAndNegative);
if (option == MessageDialogResult.Affirmative)
{
_canNavigate = true;
_navigationService.Navigate(e.Uri);
}
else _canNavigate = false;
}
else
{
_canNavigate = false;
}
}