Xml rss阅读器中的NullReferenceException
我正在为Windows Phone构建一个新闻阅读器,我已经成功地做到了这一点。然而,我想得到头条新闻。我正在尝试以下代码:Xml rss阅读器中的NullReferenceException,xml,windows-phone-7,windows-phone-8,rss,windows-phone,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.Wind
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”,我的问题是:为什么
问候,,
Erik我通过直接访问RSSdata修复了它,并将其转换为一个列表-然后我访问了它的Title属性,如下所示:
var toparticle = RSSdata.ToList()[1] as RSSItem;
toparticleTextBlock.Text = toparticle.Title.ToString(); // Put the top article into the toparticleTextBlock
很难说。您是否调试并检查了什么是空的,而您期望的不是空的?如果非要我猜的话,那是因为你的RSS在你的UI加载之前就已经下载了,但这也是一个猜测。如果您进行调试,发现情况就是这样,那么您将不得不推迟填充UI,直到它加载完毕。您可以使用Dispatcher将方法排队,以足够低的优先级填充UI,使其在加载后运行。什么是
null
Items
很可能是零基的,无论如何我都会直接使用RSSData
。topItem
上是否有Title
属性?是否有Title属性?是的,我将直接使用RSSData进行检查。我还将查看下载是否在UI加载之前完成。我是否可以将toparticleTextBlock.Text更改放置在页面的Load()调用中的try语句内的重复循环中?查看我的解决方案