我正在尝试在我放置在我的 WP7 应用程序中的 Web 浏览器控件中执行正确的回栈导航。Web 浏览器位于一个自定义控件中,我在其中实现了导航方法,然后将此控件放置在我的应用程序的一个页面中。导航似乎工作正常,除了 backstack。有时它会返回上一页,而其他时候(当它不应该这样做时)它会关闭应用程序。到目前为止,这是我的实现:
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)");
}
浏览器页面.xaml.cs
protected override void OnBackKeyPress(System.ComponentModel.CancelEventArgs e)
{
if (TheBrowser.CanNavigateBack)
{
e.Cancel = true;
TheBrowser.NavigateBack();
}
else
base.OnBackKeyPress(e);
}
注意:在我的网络浏览器中启用了 Javascript,并且所有其他导航都正常工作。我的问题是,有时网络浏览器可以正确导航回来,而其他时候它不起作用并一起关闭。我的执行有问题吗?我可以做些什么来解决这个问题?