サーバー上の画像取得とRSSのデータを表示する

2011年8月5日(金)
PROJECT KySS

ロジックコードを記述する

リスト6 (MainPage.xaml.vb)

1Option Strict On
2 
3LINQ to XMLを利用するためSystem.Xml.Linq名前空間をインポートします。
4Imports System.Xml.Linq
5Partial Public Class MainPage
6  Inherits PhoneApplicationPage
7 
8~コード略~

ページが読み込まれた時の処理

01ReadXmldocクラスの新しいインスタンスmyReadXmldoc変数を宣言します。
02文字列型の新しいリストである、titleList変数を宣言します。
03ReadXmldocクラスのインスタンスmyReadXmldocでCodeRecipeDoc関数を呼び出します。Descendantsメソッドで取得した<タイトル>要素のコレクションに対して、各要素を変数 result に格納しながら以下の処理を実行します。
04リストであるtitleListオブジェクトに、<タイトル>要素の内容をAddメソッドで追加していきます。ListBoxのItemsSourceプロパティにtitleListオブジェクトを指定します。これで、分類の一覧が表示されます。
05  Private Sub MainPage_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
06    Dim myReadXmldoc As New ReadXmldoc
07    Dim titleList As New List(Of String)
08  
09    For Each result In From c In myReadXmldoc.CodeRecipeDoc.Descendants("タイトル") Select c
10      titleList.Add(result.Value)
11    Next
12    ListBox1.ItemsSource = titleList
13  End Sub

ListBoxから項目が選択された時の処理

1ListBoxより選択された項目のインデックスを文字列に変換して、変数myIndexに格納しておきます。
2NavigationService.Navigateメソッドで、CodeRecipeIndex.xamlに遷移します。その際、Indexというキーワードに変数myIndexの値を引数として持たせています
3  Private Sub ListBox1_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles ListBox1.SelectionChanged
4    Dim myIndex As String = ListBox1.SelectedIndex.ToString
5    NavigationService.Navigate(New Uri("/CodeRecipeIndex.xaml?Index=" & myIndex, UriKind.Relative))
6  End Sub
7End Class

ソリューションエクスプローラー内のCodeRecipeIndex.xamlを展開し、表示されるCodeRecipeIndex.xaml.vbをダブルクリックしてリスト7のロジックコードを記述します。

リスト7 (CodeRecipeIndex.xaml.vb)

01Option Strict On
02Imports System.Xml.Linq
03 
04Partial Public Class CodeRecipeIndex
05  Inherits PhoneApplicationPage
06~コード略~
07 
08ReadXmldocクラスの新しいインスタンスmyReadXmldocをメンバ変数として宣言します。
09  Dim myReadXmldoc As New ReadXmldoc
10文字列型の新しいリストであるuriListをメンバ変数として宣言します。
11  Dim uriList As New List(Of String)
12数値型のメンバ変数Indexを宣言します。このIndexには、エミュレーターのBack(←)ボタンがクリックされて、該当ページに遷移する際に、MainPage.xamlの分類で選択された項目のインデックス番号が格納され、各遷移ページに渡されます。
13  Dim Index As Integer = 0

画面の遷移で移動した時に最初に呼ばれるイベント

01ここで、MainPage.xamlから渡された文字データを受け取ります。文字データはNavigationContextのQueryStringにDictionary として提供されます。
02ContainsKeyメソッドで、指定したキー(ここでは、Index)が Dictionary に格納されているかどうかを判断し、格納されている場合は、数値に変換して、myParam(“Index”)の値を変数Indexに格納します。
03新しい、WebClientのインスタンス、myWebClientを生成します。
04ReadXmldocクラスのインスタンスmyReadXmldocでCodeRecipeDoc関数を呼び出します。Descendantsメソッドで取得した、変数Indexに対応する<タイトル>要素の、”uri”属性の値を取得して、変数myUriに格納します。
05OpenReadAsyncメソッドで、指定したURIを開きます。絶対URIで指定します。OpenReadAsyncメソッドは、指定したリソースに対する読み取り可能なストリームを開くメソッドです。
06AddHandlerメソッドで、OpenReadCompletedイベントハンドラを追加します。OpenReadCompletedイベントは、非同期のリソース読み取り操作の完了時に発生します。
07OpenReadCompletedイベント内では以下の処理を行います。
08リソースの読み取りに失敗した場合は、エラーメッセージボックスを表示させます。
09リソースの読み取りに成功した場合は、XElement.Loadメソッドでリソース(resultArgs.Result)を読み込みます。文字列型の新しいリストであるtitleListを生成します。Descendantsメソッドで取得した<item>要素のコレクションに対して、各要素を変数 result に格納しながら以下の処理を実行します。
10titleListオブジェクトに<title>要素の内容を追加し、uriListオブジェクトに<link>要素の内容を追加していきます。ListBoxのItemsSourceプロパティにtitleListオブジェクトを指定します。目次が表示されます。
11  Protected Overrides Sub OnNavigatedTo(ByVal e As System.Windows.Navigation.NavigationEventArgs)
12    Dim myParam As IDictionary(Of String, String) = Me.NavigationContext.QueryString
13    If myParam.ContainsKey("Index") = True Then
14      Index = Integer.Parse(myParam("Index"))
15      Dim myWebClient As New WebClient
16   
17      AddHandler myWebClient.OpenReadCompleted, Sub(resultSender As Object, resultArgs As OpenReadCompletedEventArgs)
18                                                If resultArgs.Error Is Nothing = False Then
19                                                     MessageBox.Show("RSSファイル読み取りエラー")
20                                                     Exit Sub
21                                                Else
22                                                     Dim doc As XElement = XElement.Load(resultArgs.Result)
23                                                     Dim titleList As New List(Of String)
24                                                     For Each result In From c In doc.Descendants("item") Select c
25   
26  titleList.Add(result.Element("title").Value)
27   
28  uriList.Add(result.Element("link").Value)
29                                                     Next
30   
31                                                     ListBox1.ItemsSource = titleList
32                                                 End If
33                                              End Sub
34      Dim myUri As String = myReadXmldoc.CodeRecipeDoc.Descendants("タイトル")(Index).Attribute("uri").Value
35      myWebClient.OpenReadAsync(New Uri(myUri, UriKind.Absolute))
36    End If
37    MyBase.OnNavigatedTo(e)
38  End Sub

エミュレーターのBack(←)ボタンのイベントを上書きする処理

1エミュレーターの持っている本来のBack処理を、e.Cancel=Trueで無効とします。
2NavigationService.NavigateメソッドでMainPage.xamlに遷移します。
3Protected Overrides Subと入力すると、インテリセンス機能が働き、イベントの一覧が表示されますので、その中から選択してください。
4  Protected Overrides Sub OnBackKeyPress(ByVal e As System.ComponentModel.CancelEventArgs)
5    e.Cancel = True
6    Me.NavigationService.Navigate(New Uri("/MainPage.xaml", UriKind.Relative))
7    MyBase.OnBackKeyPress(e)
8  End Sub

ListBoxから項目(目次)を選択した時の処理

1ListBoxより選択された項目名を変数selectTitleに格納し、Replaceメソッドで[C#]という文字を[CSharp]という文字に置換します。#という文字が含まれていると、PageView.xamlに遷移した際エラーになるためです。
2NavigationService.NavigateメソッドでPageView.xamlに遷移します。その際、TitleキーワードにselectTitle、UriキーワードにListBoxより選択されたインデックスに該当するuriList、そして、Indexキーワードにメンバ変数Indexの値を渡しています。IndexにはMainPage.xamlの分類で選択された項目のインデックス番号が格納されています。
3  Private Sub ListBox1_SelectionChanged(ByVal sender As Object, ByVal e As System.Windows.Controls.SelectionChangedEventArgs) Handles ListBox1.SelectionChanged
4    Dim selectTitle As String = ListBox1.SelectedItem.ToString
5    selectTitle = selectTitle.Replace("[C#]", "[CSharp]")
6    NavigationService.Navigate(New Uri("/PageView.xaml?Title=" & selectTitle & "&Uri=" & uriList(ListBox1.SelectedIndex) & "&Index=" & Index, UriKind.Relative))
7  End Sub

エミュレーターの表示方向が変化する時に発生するイベント

1エミュレーターが横向きになった時はListBoxのWidthの値を広くとります。
2  Private Sub CodeRecipeIndex_OrientationChanged(sender As Object, e As Microsoft.Phone.Controls.OrientationChangedEventArgs) Handles MyBase.OrientationChanged
3    ListBox1.Width = Me.ActualWidth
4  End Sub
5End Class

ソリューションエクスプローラー内のPageView.xamlを展開し、表示されるPageView.xaml.vbをダブルクリックしてリスト8のロジックコードを記述します。

リスト8 (PageView.xaml.vb)

1Option Strict On
2 
3Partial Public Class PageView
4  Inherits PhoneApplicationPage
5~コード略~
6  Dim Index As Integer = 0

ページが読み込まれた時の処理

01CodeRecipeIndex.xamlから渡された文字データを受け取ります。文字データはNavigationContextのQueryStringにDictionary として提供されます。myParam(“Title”)でTitleパラメータに渡された値を受け取り、変数myTitleに格納します。myParam(“Index”)でIndexに渡された値を、数値に変換してメンバ変数Indexに格納します。PageTitleという名前のTextBlockにmyTitle変数の値を表示します。CodeRecipeIndex.xamlから渡された目次が表示されます。myParam(“Uri”)でUriパラメータに渡された値を受け取り、変数myUriに格納します。WebBrowserのNavigateメソッドにmyUriの値を絶対URIで指定します。WebBrowser内にサイトが表示されます。
02  Private Sub PageView_Loaded(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs) Handles MyBase.Loaded
03    Dim myParam As IDictionary(Of String, String) = Me.NavigationContext.QueryString
04  
05    Dim myTitle As String = myParam("Title")
06    Index = Integer.Parse(myParam("Index"))
07    PageTitle.Text = myTitle
08    Dim myUri As String = myParam("Uri")
09    WebBrowser1.Navigate(New Uri(myUri, UriKind.Absolute))
10  End Sub

エミュレーターのBack(←)ボタンのイベントを上書きする処理

1エミュレーターの持っている本来のBack処理を、e.Cancel=Trueで無効とします。
2NavigationService.NavigateメソッドでCodeRecipeIndex.xamlに遷移します。引数にメンバ変数Indexの値を渡しています。IndexにはMainPage.xamlの分類で選択された項目のインデックス番号が格納されています。
3Protected Overrides Subと入力すると、インテリセンス機能が働き、イベントの一覧が表示されますので、その中から選択してください。
4  Protected Overrides Sub OnBackKeyPress(ByVal e As System.ComponentModel.CancelEventArgs)
5    Me.NavigationService.Navigate(New Uri("/CodeRecipeIndex.xaml?Index=" & Index, UriKind.Relative))
6    e.Cancel = True
7    MyBase.OnBackKeyPress(e)
8  End Sub

エミュレーターの表示方向が変化する時に発生するイベント

1エミュレーターが横向きになった時はWebBrowserのWidthの値を広くとります。
2  Private Sub PageView_OrientationChanged(sender As Object, e As Microsoft.Phone.Controls.OrientationChangedEventArgs) Handles MyBase.OrientationChanged
3  WebBrowser1.Width = Me.ActualWidth
4  End Sub
5End Class
  • 「サーバー上の画像取得とRSSのデータを表示する」サンプルプログラム_1

  • 「サーバー上の画像取得とRSSのデータを表示する」サンプルプログラム_2

四国のSOHO。薬師寺国安(VBプログラマ)と、薬師寺聖(デザイナ、エンジニア)によるコラボレーション・ユニット。1997年6月、Dynamic HTMLとDirectAnimationの普及を目的として結成。共同開発やユニット名義での執筆活動を行う。XMLおよび.NETに関する著書や連載多数。最新刊は「Silverlight実践プログラミング」両名とも、Microsoft MVP for Development Platforms - Client App Dev (Oct 2003-Sep 2012)。http://www.PROJECTKySS.NET/

連載バックナンバー

Think ITメルマガ会員登録受付中

Think ITでは、技術情報が詰まったメールマガジン「Think IT Weekly」の配信サービスを提供しています。メルマガ会員登録を済ませれば、メルマガだけでなく、さまざまな限定特典を入手できるようになります。

Think ITメルマガ会員のサービス内容を見る

他にもこの記事が読まれています