我正試圖在我放入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期間攔截意味着您可以將按鍵+按鍵事件組合在一起,因此瀏覽器可能會返回並運行代碼,導致錯誤或雙擊導航。讓我?嘗試攔截後退鍵,並將上面的代碼放在該事件中,讓我知道它是如何發生的。 –