导航回来的WP7 NullReferenceException

时间:2012-04-14 02:18:50

标签: c# windows-phone-7

我尝试使用RSS阅读器中的以下代码导航回到以前的MainPage.xaml时,我得到一个空引用异常。有人可以通过建议我需要做些什么来帮助我来避免这个错误吗?

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

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题。错误发生在我的MainPage脚本中。我已将datacontext设置移动到主脚本中,现在不再抛出错误