win phone 8 NavigationContext 報NullReferenceException解決方案

 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);
        }



NullReferenceException

NullReferenceException

NullReferenceException

發佈了87 篇原創文章 · 獲贊 18 · 訪問量 26萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章