在以下async OnNavigating处理程序中,将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;
}
}
答案 0 :(得分:1)
使用决策变量_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;
}
}