我正试图在我放入WP7应用程序的Web浏览器控件中执行正确的后退堆栈导航。 Web浏览器位于一个自定义控件中,在该控件中实现了导航方法,然后将此控件放置在应用程序的页面中。导航似乎正常工作,除了后台。有时会回到上一页,其他时间(当它不应该)时,会关闭应用程序。这里是我的执行至今:如何正确处理Web浏览器控制返回导航
WebBrowser.cs(用户控件)
//The navigation urls of the browser.
private readonly Stack<Uri> _NavigatingUrls = new Stack<Uri>();
//The history for the browser
private readonly ObservableCollection<string> _History =
new ObservableCollection<string>();
//Flag to check if the browser is navigating back.
bool _IsNavigatingBackward = false;
/// <summary>
/// Gets the History property for the browser.
/// </summary>
public ObservableCollection<string> History
{
get { return _History; }
}
/// <summary>
/// CanNavigateBack Dependency Property
/// </summary>
public static readonly DependencyProperty CanNavigateBackProperty =
DependencyProperty.Register("CanNavigateBack", typeof(bool),
typeof(FullWebBrowser), new PropertyMetadata((bool)false));
/// <summary>
/// Gets or sets the CanNavigateBack property. This dependency property
/// indicates whether the browser can go back.
/// </summary>
public bool CanNavigateBack
{
get { return (bool)GetValue(CanNavigateBackProperty); }
set { SetValue(CanNavigateBackProperty, value); }
}
void TheWebBrowser_Navigating(object sender,
Microsoft.Phone.Controls.NavigatingEventArgs e)
{
//show the progress bar while navigating
}
void TheWebBrowser_Navigated(object sender,
System.Windows.Navigation.NavigationEventArgs e)
{
//If we are Navigating Backward and we Can Navigate back,
//remove the last uri from the stack.
if (_IsNavigatingBackward == true && CanNavigateBack)
_NavigatingUrls.Pop();
//Else we are navigating forward so we need to add the uri
//to the stack.
else
{
_NavigatingUrls.Push(e.Uri);
//If we do not have the navigated uri in our history
//we add it.
if (!_History.Contains(e.Uri.ToString()))
_History.Add(e.Uri.ToString());
}
//If there is one address left you can't go back.
if (_NavigatingUrls.Count > 1)
CanNavigateBack = true;
else
CanNavigateBack = false;
//Finally we hide the progress bar.
ShowProgress = false;
}
/// <summary>
/// Used to navigate back.
/// </summary>
public void NavigateBack()
{
_IsNavigatingBackward = true;
TheWebBrowser.InvokeScript("eval", "history.go(-1)");
}
BrowserPage.xaml.cs
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
if (TheBrowser.CanNavigateBack)
{
e.Cancel = true;
TheBrowser.NavigateBack();
}
else
base.OnBackKeyPress(e);
}
注:JavaScript是在web浏览器我和所有其他的导航工程启用正确。我的问题是,有时网页浏览器会正确导航,而其他时间则无法正常显示,并一起关闭。我的推动力有问题吗?我可以做些什么来解决这个问题?
对不起,在长时间的响应延迟。我曾尝试删除else语句,但仍然出现同样的问题。有时导航是正确的,有时候应用程序不会使用Web浏览器从页面导航到前一页。 – Matthew
@Mthethew然后,当你实际按下后退按钮时,你意识到浏览器开始后退导航,所以如果你按下后退按钮并按住它,它将继续前进直到没有东西可以返回。因此在KeyPress期间拦截意味着您可以将按键+按键事件组合在一起,因此浏览器可能会返回并运行代码,导致错误或双击导航。让我?尝试拦截后退键,并将上面的代码放在该事件中,让我知道它是如何发生的。 –