private void preview_detail(object sender, RoutedEventArgs e)
{
VehicleFromAd vehicleFromAd = (VehicleFromAd)(sender as MenuItem).Tag;
NavigationService.Navigate(new Uri("/Preview.xaml?carId=" + vehicleFromAd.id, UriKind.Relative));
}
這裏在xaml頁面發生preview_detail點擊事件時將跳轉Preview.xaml頁面
起初我代碼是這麼寫的:
public partial class Preview : PhoneApplicationPage
{
private int carId ;
// 構造函數
public Preview()
{
InitializeComponent();
// 用於本地化 ApplicationBar 的示例代碼
//BuildLocalizedApplicationBar();
if (NavigationContext.QueryString.ContainsKey("carId"))
{
carId = int.Parse(NavigationContext.QueryString["carId"]);
}
webBrowser1.Loaded += WebBrowser_OnLoaded;
}
//protected override void OnNavigatedTo(NavigationEventArgs e) {
// if (NavigationContext.QueryString.ContainsKey("carId"))
// {
// carId = int.Parse(NavigationContext.QueryString["carId"]);
// }
// webBrowser1.Loaded += WebBrowser_OnLoaded;
//}
private void WebBrowser_OnLoaded(object sender, RoutedEventArgs e)
{
webBrowser1.Source = new Uri("http://m.51auto.com/car_info.html?car_id="+carId, UriKind.Absolute);
}
結果在NavigationContext時發生了NullReferenceException異常,查閱相關資料才知道是調用時機的問題,在 OnNavigatedTo 調用之後纔會NavigationContext纔有值。在page的構造函數裏調用,太早了。
那咱就修改如下,一切如預期般靠譜,嘿嘿,沒深入理解的後果!
public partial class Preview : PhoneApplicationPage
{
private int carId ;
// 構造函數
public Preview()
{
InitializeComponent();
// 用於本地化 ApplicationBar 的示例代碼
//BuildLocalizedApplicationBar();
//if (NavigationContext.QueryString.ContainsKey("carId"))
//{
// carId = int.Parse(NavigationContext.QueryString["carId"]);
//}
//webBrowser1.Loaded += WebBrowser_OnLoaded;
}
protected override void OnNavigatedTo(NavigationEventArgs e)
{
if (NavigationContext.QueryString.ContainsKey("carId"))
{
carId = int.Parse(NavigationContext.QueryString["carId"]);
}
webBrowser1.Loaded += WebBrowser_OnLoaded;
}
private void WebBrowser_OnLoaded(object sender, RoutedEventArgs e)
{
webBrowser1.Source = new Uri("http://m.51auto.com/car_info.html?car_id="+carId, UriKind.Absolute);
}