2012-04-14 65 views
0

我在使用下面的代碼從我的RSS閱讀器嘗試導航回到前面的MainPage.xaml時收到空引用異常。有人可以幫助我建議我需要做什麼來避免這個錯誤?WP7 NullReferenceException在導航上返回

public partial class FeedDetailsPage : PhoneApplicationPage 
{ 
    object _selectedFeedItem; 
    object _selectedFeed; 

    public FeedDetailsPage() 
    { 
     InitializeComponent(); 
     Loaded += new RoutedEventHandler(PhoneApplicationPage_Loaded); 
     LoadFeed(); 
    } 

    private void LoadFeed() 
    { 
     FrameworkElement root = Application.Current.RootVisual as FrameworkElement; 
     var currentFeed = root.DataContext as ATP_Tennis_App.ViewModels.FeedViewModel; 
     WebClient wc = new WebClient(); 
     wc.DownloadStringCompleted += new DownloadStringCompletedEventHandler(wc_DownloadStringCompleted); 
     wc.DownloadStringAsync(new Uri(currentFeed.FeedUrl)); 
     _selectedFeed = currentFeed; 
    } 

    void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
    { 
     // if (e.Error != null) { return; } 

     var rssFeed = XElement.Parse(e.Result); 

     var currentFeed = this.DataContext as ATP_Tennis_App.ViewModels.FeedViewModel; 
     var items = from item in rssFeed.Descendants("item") 

        select new ATP_Tennis_App.ViewModels.FeedItemViewModel() 
        { 

         Title = item.Element("title").Value, 
         DatePublished = DateTime.Parse(item.Element("pubDate").Value), 
         Url = item.Element("link").Value, 
         Description = item.Element("description").Value 
        }; 
     foreach (var item in items) 
      currentFeed.Items.Add(item); 

    } 

    private void PhoneApplicationPage_BackKeyPress(object sender, System.ComponentModel.CancelEventArgs e) 
    { 
     // Cancel default navigation 

     e.Cancel = true; 
     PhoneApplicationFrame root = (PhoneApplicationFrame)Application.Current.RootVisual; 
     root.GoBack(); 



    } 


    private void PhoneApplicationPage_Loaded(object sender, RoutedEventArgs e) 
    { 
     this.DataContext = _selectedFeed; 
    } 



    private void lstFeeds_SelectionChanged(object sender, SelectionChangedEventArgs e) 
    { 
     _selectedFeedItem = (sender as ListBox).SelectedItem; 
     NavigationService.Navigate(new Uri("/FeedItemDetailsPage.xaml", UriKind.Relative)); 
     FrameworkElement root = Application.Current.RootVisual as FrameworkElement; 
     root.DataContext = _selectedFeedItem; 
    } 


} 

拋出異常上線

wc.DownloadStringAsync(new Uri(currentFeed.FeedUrl)); 
+0

什麼是您的完整異常堆棧跟蹤?哪一行代碼正在拋出NRE? – ColinE 2012-04-14 06:20:44

+0

ColinE,我已更新問題以顯示拋出異常的行 – 2012-04-24 12:25:40

+0

只是一個猜測:您的currentFeed == null?當根的DataContext爲null或不是FeedViewModel時,可能會發生這種情況。你在哪裏設置DataContext? – 2012-04-24 12:28:00

回答

0

我已經解決了這一點。該錯誤在我的MainPage腳本中。我已將datacontext設置移到主腳本中,現在不再拋出錯誤