Search This Blog

Tuesday, June 3, 2014

WPF Read RSS feed and bind to DataGrid

WPF > SyndicationFeed > Read RSS feed

Read RSS feed and bind to DataGrid



XAML


<Window x:Class="Feed.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="Rss Feed" Height="670" Width="737" Loaded="Window_Loaded">
    <Grid>
        <DataGrid ItemsSource="{Binding RssFeedList}"  AutoGenerateColumns="False" IsReadOnly="True">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Title" Binding="{Binding Title}"/>
            </DataGrid.Columns>
        </DataGrid>
      
    </Grid>
</Window>


c#

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace Feed
{
    public class RssFeed
    {
        public string Title { get; set; }
    }
      
      
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public ObservableCollection<RssFeed> RssFeedList { get; set; }
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            string feedUrl = "http://rss.cnn.com/rss/cnn_latest.rss";
            System.Xml.XmlReader reader = System.Xml.XmlReader.Create(feedUrl);

            System.ServiceModel.Syndication.SyndicationFeed feed = System.ServiceModel.Syndication.SyndicationFeed.Load(reader);
            RssFeedList = new ObservableCollection<RssFeed>();
            foreach (var item in feed.Items)
            {
                RssFeed rf = new RssFeed();
                rf.Title = item.Title.Text.ToString();
                RssFeedList.Add(rf);
            }
            this.DataContext = this;
        }
    }
}