2014-03-11 3 views
0

Windows Phone 용 뉴스 리더를 구축 중이며이를 성공적으로 관리했습니다. 그러나 나는 최고 뉴스 기사를 얻고 싶다.RSS 리더에서 NullReferenceException이 발생했습니다.

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

하지만 맨 위 항목을 가져오고 'System.NullReferenceException'가 발생 TextBlock에로를두고 내 질문은 라인 :이 코드를 시도하고 그 이유는 무엇입니까?

안부, 에릭

+0

하드 말할 수 있습니다. 디버그하고 null이 아닌 null이 무엇인지 확인 했습니까? 추측해야만한다면 UI가로드되기 전에 RSS가 다운로드 되었기 때문입니다.하지만 다시 추측 할 수 있습니다. 디버깅하는 경우에 해당하는 경우 UI로드가 완료 될 때까지 UI를 채워야합니다. Dispatcher를 사용하여로드 된 후 실행되는 우선 순위가 낮은 UI를 채울 수있는 메소드를 대기열에 추가합니다. – Will

+0

'null'이란 무엇입니까? 'Items'는 0 기반이 될 가능성이 높기 때문에 직접 RSSData를 사용합니다. 'topItem'에'Title' 속성이 있습니까? – WiredPrairie

+0

Title 속성이 있습니다. RSSData를 직접 사용하여 확인합니다. 또한 UI가로드되기 전에 다운로드가 완료되는지 살펴볼 것입니다. – Erik

답변

0

내가 직접 RSSdata에 접속하여 고정 목록에 그것을 설정 - 나는 그것이 Title 속성이처럼 액세스 :

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