построение наблюдаемой коллекции с помощью элементов rss xml - PullRequest
0 голосов
/ 25 июля 2011

Проще говоря, у меня есть свой класс RSSItem и мой класс RSSService, а также кнопка для их загрузки. Как я могу загрузить их в наблюдаемую коллекцию, чтобы я мог манипулировать данными?

пространство имен и кнопка для загрузки кода:

public partial class UserSubmitted : PhoneApplicationPage
{
    private const string WindowsPhoneBlogPosts = "http://www.example/feed.xml";

    private void Button_Click(object sender, RoutedEventArgs e)
    {
        RssService.GetRssItems(
            WindowsPhoneBlogPosts,
            (items) => { listbox.ItemsSource = items; },
            (exception) => { MessageBox.Show(exception.Message); },
            null
            );
    }
}

Код товара:

namespace WindowsPhone.Helpers
{
public class RssItem
{
    /// <summary>
    /// Initializes a new instance of the <see cref="RssItem"/> class.
    /// </summary>
    /// <param name="title">The title.</param>
    /// <param name="summary">The summary.</param>
    /// <param name="publishedDate">The published date.</param>
    /// <param name="url">The URL.</param>
    public RssItem(string title, string summary, string publishedDate, string url)
    {
        Title = title;
        Summary = summary;
        PublishedDate = publishedDate;
        Url = url;


        // Get plain text from html
        PlainSummary = HttpUtility.HtmlDecode(Regex.Replace(summary, "<[^>]+?>", ""));
    }

    /// <summary>
    /// Gets or sets the title.
    /// </summary>
    /// <value>The title.</value>
    public string Title { get; set; }

    /// <summary>
    /// Gets or sets the summary.
    /// </summary>
    /// <value>The summary.</value>
    public string Summary { get; set; }

    /// <summary>
    /// Gets or sets the published date.
    /// </summary>
    /// <value>The published date.</value>
    public string PublishedDate { get; set; }

    /// <summary>
    /// Gets or sets the URL.
    /// </summary>
    /// <value>The URL.</value>
    public string Url { get; set; }

    /// <summary>
    /// Gets or sets the plain summary.
    /// </summary>
    /// <value>The plain summary.</value>
    public string PlainSummary { get; set; }
   }
 }

сервисный код:

namespace WindowsPhone.Helpers
{ 
public static class RssService
{


    /// Gets the RSS items.
    /// <param name="rssFeed">The RSS feed.</param>
    /// <param name="onGetRssItemsCompleted">The on get RSS items completed.</param>
    /// <param name="onError">The on error.</param>
    public static void GetRssItems(string rssFeed, Action<IEnumerable<RssItem>> onGetRssItemsCompleted = null, Action<Exception> onError = null, Action onFinally = null)
    {
        WebClient webClient = new WebClient();

        // register on download complete event
        webClient.OpenReadCompleted += delegate(object sender, OpenReadCompletedEventArgs e)
        {
            try
            {
                // report error
                if (e.Error != null)
                {
                    if (onError != null)
                    {
                        onError(e.Error);
                    }
                    return;
                }

                // convert rss result to model
                List<RssItem> rssItems = new List<RssItem>();
                Stream stream = e.Result;
                XmlReader response = XmlReader.Create(stream);
                SyndicationFeed feeds = SyndicationFeed.Load(response);


                foreach (SyndicationItem f in feeds.Items)
                {
                    RssItem rssItem = new RssItem(f.Title.Text, f.Summary.Text, f.PublishDate.ToString(), f.Links[0].Uri.AbsoluteUri);               
                    rssItems.Add(rssItem);


                }

                // notify completed callback
                if (onGetRssItemsCompleted != null)
                {
                    onGetRssItemsCompleted(rssItems);

                }
            }
            finally
            {
                // notify finally callback
                if (onFinally != null)
                {
                    onFinally();
                }
            }
        };

        webClient.OpenReadAsync(new Uri(rssFeed));
    }
  }
}

1 Ответ

1 голос
/ 25 июля 2011

Вы можете создать ObservableCollection, используя ключевые слова 'new' следующим образом:

ObservableCollection<RssItem> rssItems = new ObservableCollection<RssItem>();

Затем вы можете добавить их с помощью метода Add:

RssItem rssItem = new RssItem( /* initializationcode here */ );
rssItems.Add(rssItem);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...