rss阅读器中的NullReferenceException

时间:2014-03-11 14:07:32

标签: xml windows-phone-7 windows-phone-8 rss windows-phone

我正在为Windows Phone构建新闻阅读器,并且我已经成功地管理了它。但是我想获得最新消息。我正在尝试这段代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.Xml.Linq;

namespace App_Name
{
public partial class MainPage : PhoneApplicationPage
{
    WebClient client = new WebClient();
    // Constructor
    public MainPage()
    {
        InitializeComponent();

        // Set the data context of the listbox control to the sample data
        DataContext = App.ViewModel;
        this.Loaded += new RoutedEventHandler(MainPage_Loaded);

        // Download XML
        client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted);
        client.DownloadStringAsync(new Uri("https://www.vg.no/rss/create.php?categories=125,10,12&keywords=&limit=10"));
    }

    private void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
    {
        var RSSdata = from rss in XElement.Parse(e.Result).Descendants("item")
                      select new RSSItem
                          {
                              Title = rss.Element("title").Value,
                              PubDate = rss.Element("pubDate").Value,
                              Description = rss.Element("description").Value
                          };
        newsListBox.ItemsSource = RSSdata;
        var topItem = newsListBox.Items[1] as RSSItem; // Get the top article
        toparticleTextBlock.Text = topItem.Title.ToString(); // Put the top article into the toparticleTextBlock
    }

    // Load data for the ViewModel Items
    private void MainPage_Loaded(object sender, RoutedEventArgs e)
    {
        if (!App.ViewModel.IsDataLoaded)
        {
            App.ViewModel.LoadData();
        }
    }
}
}

但是获取顶部项并将其放入TextBlock的行会抛出一个' System.NullReferenceException'我的问题是:为什么?

此致 埃里克

1 个答案:

答案 0 :(得分:0)

我通过直接访问RSSdata并将其转换为List来修复它 - 然后我访问了它的Title属性,如下所示:

            var toparticle = RSSdata.ToList()[1] as RSSItem;
        toparticleTextBlock.Text = toparticle.Title.ToString(); // Put the top article into the toparticleTextBlock