かずきのBlog

C#やJavaやRubyとメモ書き

目次

Blog 利用状況

ニュース

わんくまBlogが不安定になったため、前に書いてたはてなダイアリーにメインを移動します。
かずきのBlog@Hatena
技術的なネタは、こちらにも、はてなへのリンクという形で掲載しますが、雑多ネタははてなダイアリーだけに掲載することが多いと思います。
コメント
プログラマ的自己紹介
お気に入りのツール/IDE
プロフィール
経歴
広告
アクセサリ

書庫

日記カテゴリ

[C#][WPF]Rss Reader(簡易版)を作ってみよう! その5

前回までで、見た目とRSS取得処理が完成した。
今回は、これを繋いでいってみようと思う。

とりあえず、WpfRssReaderプロジェクトに、RssReaderLibプロジェクトの参照を追加する。これが無いとはじまらないからね。
そして、画面のModelに相当するクラスを1つこさえる。名前は、なんのヒネリもなくRssReaderModelにしてみた。

namespace WpfRssReader
{
    public class RssReaderModel
    {
    }
}

これを、画面のDataContextに設定しておく。

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
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;
using System.ComponentModel;

namespace WpfRssReader
{
    /// <summary>
    /// Window1.xaml の相互作用ロジック
    /// </summary>
    public partial class RssReaderWindow : Window
    {
        public RssReaderWindow()
        {
            InitializeComponent();
            var model = new RssReaderModel();
            DataContext = model;
        }

    }
}

次は、Modelの実装!!
RSSのフィードは、RssInfosというプロパティで公開する形にしようと思う。
AddFeed(Uri)でフィードを追加する。

フィードの追加は、時間がかかると思うので、BackgroundWorkerを使ってバックグラウンドで行うようにしてみた。
ということでコード。

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using RssReaderLib;

namespace WpfRssReader
{
    public class RssReaderModel
    {
        public IList<RssInfo> RssInfos { get; private set; }

        public RssReaderModel()
        {
            RssInfos = new ObservableCollection<RssInfo>();
        }

        public void AddFeed(Uri uri)
        {
            var worker = new BackgroundWorker();
            worker.DoWork += (sender, e) =>
                {
                    var reader = new RssReader();
                    e.Result = reader.Read(uri);
                };
            worker.RunWorkerCompleted += (sender, e) =>
                {
                    var info = e.Result as RssInfo;
                    RssInfos.Add(info);
                };
            worker.RunWorkerAsync();
        }
    }
}

画面のコンストラクタで、テスト用に自分のBlogと@ITのRSSフィードを追加するコードを足した。

        public RssReaderWindow()
        {
            InitializeComponent();
            var model = new RssReaderModel();
            DataContext = model;
        }

ということで画面にバインドしてみよう!!!
まず、RSS一覧の部分にRSSのTitleを表示してみようと思う。
ListBoxのBindingにさくっと追加。

                <ListBox Style="{StaticResource rssListBoxStyle}"
                         ItemsSource="{Binding RssInfos}"
                         IsSynchronizedWithCurrentItem="True">
                </ListBox>

これを実行すると、予想通りToStringされた結果が表示される。
image

これをTitleが表示されるようにしてみようと思う。
とりあえず、DataTemplateを定義してお茶を濁す。DataTemplateは、Styleを定義してあるRssReaderStyleDictionary.xamlに定義させてもらった。

    <!-- DataTemplate -->
    <DataTemplate DataType="{x:Type RssReaderLib:RssInfo}">
        <TextBlock Text="{Binding Title}" />
    </DataTemplate>

この状態で実行すると予定通りタイトルが表示されるようになった。
image

今度は、選択されたアイテムの記事の一覧を記事一覧のListViewに表示させる。

                <ListView ItemsSource="{Binding RssInfos/Items}"
                          IsSynchronizedWithCurrentItem="True">
                    <ListView.View>
                        <GridView>
                            <GridViewColumn Header="日付" Width="120" DisplayMemberBinding="{Binding Date}" />
                            <GridViewColumn Header="タイトル" DisplayMemberBinding="{Binding Title}"/>
                            <GridViewColumn Header="リンク" DisplayMemberBinding="{Binding Link}"/>
                        </GridView>
                    </ListView.View>
                </ListView>

ポイントは、最初のItemsSourceに指定してるBinding!!スラッシュを使うと、コレクションのコレクションの…的に指定できるみたい。
これを実行すると、日付がちょっと微妙だけど一応表示される。
image

日付は後回しにして、内容に選択された記事を表示してみようと思う。
これは、ListViewで選択された記事のLinkプロパティをFrameのSouceにバインドすればOK。

                    <Frame Source="{Binding RssInfos/Items/Link}"/>

image

うっし。後は日付列にある日付をフォーマッティングするだけだ!!!
これはコンバータにお願いする。

コンバータをとりあえず実装してみた。parameterで指定したフォーマットにフォーマッティングしてくれるものにしてみたよ。

using System;
using System.Windows.Data;

namespace WpfRssReader
{
    public class DateTimeFormatConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            DateTime? date = value as DateTime?;
            if (date == null) return string.Empty;

            if (parameter == null)
            {
                return date.ToString();
            }
            return date.Value.ToString(parameter as string);
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }
    }
}

これを日付の所のBindingに設定する。

                            <GridViewColumn Header="日付" Width="120">
                                <GridViewColumn.DisplayMemberBinding>
                                    <Binding Path="Date" ConverterParameter="yyyy/MM/dd">
                                        <Binding.Converter>
                                            <WpfRssReader:DateTimeFormatConverter />
                                        </Binding.Converter>
                                    </Binding>
                                </GridViewColumn.DisplayMemberBinding>
                            </GridViewColumn>

これで、やっとモトネタの@ITの連載に追いついたっぽい。実行してみると、きちんと日付が出る!
image

満足満足。
ここまでの状態のプロジェクトはこちら

投稿日時 : 2008年4月12日 18:31

Feedback

# cheap ugg 2012/10/17 23:48 http://www.superbootonline.com

Regards for helping out, fantastic information. "The health of nations is more important than the wealth of nations." by Will Durant.

# Cheap Canada Goose 2012/10/19 15:10 http://www.supercoatsale.com

Simply a smiling visitant here to share the love (:, btw great style .

# Nike Air Jordan High Heels 2012/12/08 14:39 http://suparjordanshoes1.webs.com/

Just wanna comment on few general things, The website design and style is perfect, the content material is real good : D.

# エルメスクリスマス 2012/12/14 22:43 http://www.hermespairs.info/category/エルメスバーキン

Our admins possess a sharp eye perhaps even sharper wits - not to mention our Top Comments city enjoys an ideal read. Come play with us!

# le pliage longchamp outlet 2012/12/15 15:44 http://www.sacslongchamp2012.info

Looking forwards to perusing more!

# burberry outlet 2012/12/16 4:00 http://www.burberryuksale.info/category/burberry-u

Go thru these older items and just look on your that tickle ones own fancy.

# longchamp soldes 2012/12/17 7:31 http://www.longchampfr.info/category/longchamp-pas

Our admins have a very sharp eye and in many cases sharper senses - plus our Best Comments neighborhood enjoys an ideal read. Come play with us!

# burberry pas cher 2012/12/17 20:44 http://www.sacburberryecharpe.fr/category/foulard-

I believe I will visit this approach place just as before soon.

# http://michael-kors-canada.webnode.fr/news-/ 2012/12/18 5:37 http://michael-kors-canada.webnode.fr/

That's just what exactly earbuds usually are for.

# sacs guess 2012/12/22 17:45 http://sacsguess.monwebeden.fr

this can be something i've never actually read.

# code la redoute 2013/03/06 21:21 http://www.k77.fr/

Perhaps Graven image intends everyone to find two or three incorrect customers preceding discussion the right choice, to make sure once subsequently match the customer, i will haven't learned to end up being happier. code la redoute http://www.k77.fr/

# casquette obey 2013/03/16 7:23 http://www.b44.fr/

Legitimate friendship foresees the needs of other useful as compared to extol it happens to be special. casquette obey http://www.b44.fr/

# casquette obey 2013/03/16 10:06 http://www.a44.fr/

Correct friendship foresees the requirements of other sorts of rather than extol it's always private. casquette obey http://www.a44.fr/

# destock sport et mode 2013/03/18 8:20 http://www.ruenike.com/autres-c-25.html/

Pleasure can be described as essence it is impossible storage containers . over other people while not receiving a not many comes over your true self. destock sport et mode http://www.ruenike.com/autres-c-25.html/

# destockchine 2013/03/18 8:21 http://www.c55.fr/

Father‘r waste your time effort with a men/lovely women,so , who isn‘r prepared waste these a period of time on you. destockchine http://www.c55.fr/

# destockmania 2013/03/18 8:25 http://www.ruenike.com/foot-c-10.html/

Where exactly there is a relationship without requiring appreciate, it'll be appreciate without requiring a relationship. destockmania http://www.ruenike.com/foot-c-10.html/

# usine23 2013/03/25 5:12 http://e55.fr/

Exactly where may well relationships whilst not having passion, there'll be passion whilst not having relationships. usine23 http://e55.fr/

# Destockchine 2013/04/03 7:35 http://www.ruenike.com/vetement-femme-c-16.html/

Do not ever discuss about it all of your bliss to 1 lower lucki than you and your family. Destockchine http://www.ruenike.com/vetement-femme-c-16.html/

# Destockage vetement 2013/04/04 7:44 http://www.ruenike.com/vetement-homme-c-13.html/

Genuine companionship foresees the needs of further in lieu of promulgate it's always really. Destockage vetement http://www.ruenike.com/vetement-homme-c-13.html/

# Laredoute 2013/04/07 19:02 http://ruezee.com/

Don't talk about any well-being to one lesser privileged instead of your true self. Laredoute http://ruezee.com/

# asos 2013/04/08 15:19 http://rueree.com/

If you desire any bookkeeping with your definitely worth, remember your buddies. asos http://rueree.com/

# UElYsrMzbbsNs 2014/07/18 22:41 http://crorkz.com/

SOdDW7 Im grateful for the article post.Much thanks again. Really Great.

# TAoBQRPqYSWM 2014/10/12 5:44 matt

6FVM5t http://www.QS3PE5ZGdxC9IoVKTAPT2DBYpPkMKqfz.com

# YSQrxIIXxcrCUgpKhq 2014/10/22 5:16 goodboy

good material thanks http://5passion.com/contact.htm can i order diflucan online If the Facebook Wi-Fi program gains steam, it could be easier to find an Internet connection around town since offering it won&#8217;t be such a costly burden to businesses. Unfortunately, less savvy users might not realize they don&#8217;t have to broadcast their current coordinates to get hooked up. Some people might actually enjoy helping friends discover cool cafes by checking in. But for everyone else, just read the grey print and the web is yours, no strings attached.

# xNUsEwSxaVrorGDocy 2014/10/22 5:16 Ava

I'm at Liverpool University http://5passion.com/contact.htm diflucan 150 mg price "Training and simulation, fitness, virtual tourism, virtual tradeshows and events, meet-ups and multi-person adventures, virtual workplaces, museums, VR architecture, VR concerts," the company pointed out. "The possibilities are limitless."

# DfMSzYNcyZBnavD 2014/10/22 5:16 Luis

Are you a student? http://santafyme.com/buysildalis/ buy sildalis Statistics released yesterday by the Royal National Lifeboat Institution (RNLI) show that the charity�s volunteer lifeboat crews carried out 221 rescue launches in the region in June, July and August, compared to 172 over the same period last year � a 28.5% increase.

# KwuPIVvvdxTg 2014/10/23 0:49 Melanie

I'm on business http://www.motum.com/about-us/leadership order cytotec online The French-led invasion began in January and ended in the spring after extremists who held the north were killed or dispersed. But in a sign of a continued presence, radicals fired mortar shells at Gao, in the north, on Monday.

# eiSfORIeodytDqFbH 2014/10/23 0:49 Curt

What line of work are you in? http://djdinaregine.com/blog albenza cost His furious family and civil rights groups claim that this is not the whole truth and that, in fact, it is his low grades at school and brushes with the law that mean he will be sent home without a chance of survival.

# ODzmNSJQEsz 2014/11/03 7:16 Gabrielle

What's the exchange rate for euros? http://skin-solutions.co.nz/what-is-ipl/ bimatoprost 0.01 bak The trainee, Patrick Cau, admitted to making eight separatebomb threats targeting United Airlines, starting lastOctober and continuing for four months, according to a pleaagreement reached with federal prosecutors last week. Theagreement said the threats had caused significant disruptionsand cost United $267,912.

# YXnJoLCZpjPZPiZ 2014/11/03 7:16 Gabrielle

magic story very thanks http://skin-solutions.co.nz/what-is-ipl/ buying generic bimatoprost • The Patriots added a second touchdown on a 10-play, 62-yard drive that took 3:33 late in the second quarter and ended with a five-yard touchdown pass over the middle from Brady to Thompkins. (New England tacked on a 53-yard field goal at the end of the half from Stephen Gostkowski to finish the scoring.) Overall, it was a good start for Dobson (four catches, 35 yards) and Thompkins (2 catches, 21 yards), who combined for six catches on nine targets.

# ewplVwhpxLA 2014/11/06 7:04 Dewey

Where are you calling from? http://skin-solutions.co.nz/what-is-ipl/ order online bimatoprost without prescription "But it does, in the end, force you to ask yourself the question: 'Do I have to be here, doing this?' And when Porsche came along, I could look myself in the eye and say: 'Well, you know what, I probably don't have to do some of those things any more."

# eCaSqbwRwABBVosDfc 2014/11/06 7:04 Malcom

I quite like cooking http://skin-solutions.co.nz/what-is-ipl/ buy bimatoprost cheap To this day, Hunt credits Casey Stengel with helping him get elected because the garrulous, crafty Met manager stumped for Hunt during a mid-June trip to Pittsburgh. �He told the writers if I wasn�t starting in the All-Star game, there was something wrong,� Hunt remembers. �I was having a helluva year. I guess Casey rang a bell or two.�

# SkrkCmDXeBXDVIzLbS 2014/11/06 7:04 Timmy

Punk not dead http://skin-solutions.co.nz/what-is-ipl/ bimat bimatoprost ophthalmic solution (latisse generic) De Gregorio, who has admitted receiving 3 million euros($4.13 million) from Berlusconi and attempting to persuade othersenators to change sides, was sentenced to 20 months in jailafter plea bargaining.

# XYHyDJDgzoaOiweBq 2014/11/07 3:57 Ahmed

I live in London http://skin-solutions.co.nz/what-is-ipl/ tables bimatoprost ophthalmic solution 0.03 buy online extremely approximate The eponymous show, which airs on NBC, sees Fox playing a news anchor who gave up his gig after being diagnosed with Parkinson&#39;s. But after 5 years off the desk, Fox decides it&#39;s time to return to work.

# zldOrKPEPiRY 2014/11/07 3:57 Lewis

Free medical insurance http://skin-solutions.co.nz/what-is-ipl/ concerning assumption buying bimatoprost over the counter sufficient passage More, �Springsteen & I� offers one long valentine to fandom itself. It isolates the particular thrill of projecting your most exaggerated fantasies onto an object that may, or may not, deserve them. Of course, even the lowest star, or reality show vulgarian, can inspire awe in the besotted. But there�s no denying that, due to his particular character and ambitions, Springsteen inspires in his followers a uniquely elevated kind of delusion.

# RNjPUcbzwdDzQpuXUqt 2014/11/19 12:26 Duane

How do I get an outside line? http://afritest.net/index.php/test-issues betamethasone valerate 0.1 It has already reduced its debt load to about 51.8 billioneuros from 58 billion euros one year ago and analysts expect thegroup to announce a fall below 50 billion euros at the end ofthe second quarter. It said on Tuesday it was sticking to itsobjective of cutting debt below 47 billion euros by year-end.

# MeGVTJusJQjijz 2014/11/19 12:26 Pierre

I never went to university http://www.summerbreezecampground.com/about/ 500 Mg Tylenol By the 1960s, the mighty mainframe computer, which was then a US import, had arrived in British offices. But Simmons&#039;s vision of the computer releasing clerks from tedium wasn&#039;t quite right.

# NDTgSmxXDGQbDhRC 2014/11/20 5:29 Cleveland

I've just graduated http://www.mulotpetitjean.fr/htmlsite_fr/ metronidazole and tinidazole Erdogan has invested much political capital in the process, which has enjoyed strong public support but is increasingly attracting fierce nationalist criticism over perceived concessions to militants officially deemed terrorists.

# VHDrxuInMeDw 2014/11/21 9:35 Mckinley

Your cash is being counted http://colorjar.com/terms-and-conditions/ ventolin inhalers online no prescription Five cent coins are pictured in the air in front of the Federal Palace during an event organised by the Committee for the initiative ''CHF 2,500 monthly for everyone'' (Grundeinkommen) in Bern October 4, 2013.

# hkymeziiCSZagXbBJbh 2014/11/21 9:36 Demarcus

Yes, I love it! http://www.mypetstop.co.uk/legal/ zopiclone online nz At The Oval four years ago, England only took the upper hand in the series on the penultimate day of the series. Eight years ago, that most glorious of summers was only sealed in the final session of the final day.

# XnjpXoJJtgbSViht 2014/11/21 19:26 Freddy

I don't like pubs http://greenwoodsstatebank.com/personal-loans/ loan companies grove ok Coinbase, a virtual wallet and platform where merchants andconsumers can do business using Bitcoin, said on its websitethat it has about 282,000 users and handles 175,000 transactionsa month. The firm has raised more than $6 million.

# GTnJzzQdxTe 2014/11/21 19:27 Forest

How do you spell that? http://greenwoodsstatebank.com/personal-loans/ secured loan bad credit This site uses Facebook comments to make it easier for you to contribute. If you see a comment you would like to flag for spam or abuse, click the "x" in the upper right of it. By posting, you agree to our Terms of Use.

# skdxqHhtxHcnRx 2014/11/22 14:19 Renato

I really like swimming http://threesistersfarmtx.com/about/ buy accutane online from canada PHILADELPHIA � Eagles wideout Riley Cooper caught one touchdown pass just inside the back line of the end zone and blew past another Patriots cornerback for a second score in team drills on Tuesday afternoon.

# CqBkkYjJXXgspiRzMef 2014/11/22 14:19 Mauro

We work together http://www.northeastyouthballet.org/history/philosophy/ is 5mg of abilify a lot While a lot of their contemporaries struggled to adapt from stage to TV, Morecambe and Wise&rsquo;s conversational way of working suited the format. &ldquo;They overshadowed other acts of the time, including [Sixties entertainers] Mike and Bernie Winters,&rdquo; says Cryer. &ldquo;I remember Bernie saying: &lsquo;An act like Morecambe and Wise occurs once in a lifetime &ndash; why did it have to happen in ours?&rsquo;&rdquo;

# GyLhEahYbkIeqg 2014/11/26 22:03 Behappy

Another year http://www.acimps.org/content/blogsection/4/10/ Oxybutynin Online "Make no mistake, we would never think about supporting a treaty that is inconsistent with the rights of Americans, the rights of American citizens to be able to exercise their guaranteed rights under our constitution," he said.

# zOwHjvzMYNFBEgBwt 2018/01/07 23:07 GoldenTabs

z30aTd https://goldentabs.com/

# Illikebuisse xzguv 2021/07/04 17:00 pharmaceptica

online sildenafil without prescription https://www.pharmaceptica.com/

# re: [C#][WPF]Rss Reader(???)???????! ??5 2021/07/12 16:56 hydroxychloroquine 200 mg tab

does chloroquine work https://chloroquineorigin.com/# hydroxychloriqine

# yijhfjrwufhe 2022/05/11 14:54 rsdzcq

hydroxychloroquine sulfate tabs 200mg https://keys-chloroquineclinique.com/

# Test, just a test 2022/12/13 0:45 candipharm

canadian generic pills http://candipharm.com

タイトル
名前
Url
コメント