入力したデータを分離ストレージに保存し、一覧で表示する
今回は入力したデータを、XML形式で分離ストレージに保存し、データの一覧や、データの追加を行います。データの編集は、編集したXMLがうまく分離ストレージに保存されないので、編集処理は省いています。
このサンプルはエミュレーターで動作を確認できます。実機(IS12T)が必要条件ではありません。
まずは、このプログラムで実装する機能の動作を、下記に解説しておきます。
デバッグを開始すると、「番号、氏名、住所、電話、E-mail」の項目が表示されます。「番号」は自動的に入力されます。まだデータが1件も作成されていない状態では、[データ一覧]ボタンは使用不可となっています。データを入力して[保存]ボタンをタップすると[データ一覧]の使用が可能になります(図1)。また、[新規]ボタンの使用も不可となっています。起動直後はデータの入力が可能になっていますので、[新規]ボタンは使用不可となっています。[データ一覧]から任意のデータを表示させた時点で、[新規]ボタンの使用が可能になります(図2)。
図1:データを入力して[保存]をタップすると[データ一覧]が使用可能になる(クリックで拡大) |
図2:[データ一覧]で任意のデータを選択すると、該当するデータが表示され、[新規]ボタンの使用も可能になる (クリックで拡大) |
サンプル一式は、会員限定特典としてダウンロードできます。記事末尾をご確認ください。
実機(IS12T)で動かした動画はこちらです。
プロジェクトの作成
VS 2010のメニューから[ファイル(F)/新規作成(N)/プロジェクト(P)]を選択します。次に、「Windows Phone アプリケーション」を選択して、「名前(N)」に任意のプロジェクト名を指定します。ここでは「IsolateStorageXmlSave」という名前を付けています。Windows Phoneのバージョンは7.1を選択します。
また、XML to LINQを使用するため、VS2010メニューの「プロジェクト(P)/参照の追加(R)」から、System.Xml.Linqを追加しておいてください。
MainPage.xamlの編集とコントロールの追加
x:NameがPageTitleというTextBlockを削除します。ApplicationTitleという名前のTextBlockのTextプロパティに「分離ストレージにXMLデータを保存」と指定します。
ツールボックスからTextBlockコントロールを6個、TextBoxコントロールを4個、Buttonコントロールを4個配置します。6個のTextBlockのうち5個は項目名を表示します。残りの1個はデータの件数(番号)を表示させるのに使用します。newButtonはIsEnabledのチェックを外して、最初は使用不可としておきます。また、ichiranButtonもデータが保存されるまでは、IsEnabledのチェックを外して使用不可としておきます(図3)。
書き出されるXAMLコードはリスト1のようになります。
図3:各種コントロールを配置した(クリックで拡大) |
リスト1 書き出されたXAMLコード(MainPage.xaml)
(1)「新規」と「データ一覧」ボタンのみIsEnabledにFalseが指定され、最初は使用不可となっています。 <phone:PhoneApplicationPage x:Class="IsolateStorageXmlSave.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768" FontFamily="{StaticResource PhoneFontFamilyNormal}" FontSize="{StaticResource PhoneFontSizeNormal}" Foreground="{StaticResource PhoneForegroundBrush}" SupportedOrientations="Portrait" Orientation="Portrait" shell:SystemTray.IsVisible="True" Language="ja-JP"> <!--LayoutRoot は、全てのページ コンテンツが配置されるルート グリッドです--> <Grid x:Name="LayoutRoot" Background="Transparent"> <Grid.ColumnDefinitions> <ColumnDefinition Width="126*" /> <ColumnDefinition Width="354*" /> </Grid.ColumnDefinitions> <Grid.RowDefinitions> <RowDefinition Height="Auto"/> <RowDefinition Height="61*"/> <RowDefinition Height="59*" /> <RowDefinition Height="63*" /> <RowDefinition Height="61*" /> <RowDefinition Height="63*" /> <RowDefinition Height="126*" /> <RowDefinition Height="263*" /> </Grid.RowDefinitions> <!--TitlePanel は、アプリケーション名とページ タイトルを格納します--> <StackPanel x:Name="TitlePanel" Margin="12,17,0,28" Grid.ColumnSpan="2"> <TextBlock x:Name="ApplicationTitle" Text="分離ストレージにXMLデータを保存" Style="{StaticResource PhoneTextNormalStyle}"/> </StackPanel> <!--ContentPanel - 追加コンテンツをここに入力します--> <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0" Grid.RowSpan="7" Grid.ColumnSpan="2"> <Grid.RowDefinitions> <RowDefinition Height="*" /> <RowDefinition Height="695*" /> </Grid.RowDefinitions> <TextBlock Height="33" HorizontalAlignment="Left" Margin="32,17,0,0" Name="TextBlock1" Text="番号" VerticalAlignment="Top" Width="54" Grid.Row="1" /> <TextBlock Height="33" HorizontalAlignment="Left" Margin="32,79,0,0" Name="TextBlock2" Text="氏名" VerticalAlignment="Top" Width="54" Grid.Row="1" /> <TextBox Height="77" HorizontalAlignment="Left" Margin="128,52,0,0" Name="nameTextBox" VerticalAlignment="Top" Width="322" Grid.Row="1" /> <TextBlock Height="33" HorizontalAlignment="Left" Margin="32,142,0,0" Name="TextBlock3" Text="住所" VerticalAlignment="Top" Width="54" Grid.Row="1" /> <TextBox Height="77" HorizontalAlignment="Left" Margin="128,115,0,0" Name="addressTextBox" VerticalAlignment="Top" Width="322" Grid.Row="1" /> <TextBlock Grid.Row="1" Height="33" HorizontalAlignment="Left" Margin="32,205,0,0" Name="TextBlock4" Text="電話" VerticalAlignment="Top" Width="54" /> <TextBox Grid.Row="1" Height="77" HorizontalAlignment="Left" Margin="128,178,0,0" Name="telTextBox" VerticalAlignment="Top" Width="322" /> <TextBlock Grid.Row="1" Height="33" HorizontalAlignment="Left" Margin="32,267,0,0" Name="TextBlock5" Text="E-mail" VerticalAlignment="Top" Width="65" /> <TextBox Grid.Row="1" Height="77" HorizontalAlignment="Left" Margin="128,240,0,0" Name="mailTextBox" VerticalAlignment="Top" Width="322" /> <Button Content="キャンセル" Grid.Row="1" Height="80" HorizontalAlignment="Left" Margin="142,323,0,0" Name="cancelButton" VerticalAlignment="Top" Width="180" /> <Button Content="保存" Grid.Row="1" Height="80" HorizontalAlignment="Left" Margin="313,323,0,0" Name="saveButton1" VerticalAlignment="Top" Width="137" /> <Button Content="データ一覧" Grid.Row="1" Height="80" HorizontalAlignment="Left" Margin="6,391,0,0" Name="ichiranButton" VerticalAlignment="Top" Width="444" IsEnabled="False" /> ■(1) <TextBlock Grid.Row="1" Height="48" HorizontalAlignment="Left" Margin="142,5,0,0" Name="noTextBlock" Text="" VerticalAlignment="Top" Width="84" FontSize="26" FontWeight="Bold" /> <Button Content="新規" Grid.Row="1" Height="80" HorizontalAlignment="Left" Margin="12,323,0,0" Name="newButton" VerticalAlignment="Top" Width="143" IsEnabled="False" /> ■(1) </Grid> </Grid> <!--ApplicationBar の使用法を示すサンプル コード--> ~コード略~ </phone:PhoneApplicationPage>
次に、MainPage.xamlを展開して表示される、MainPage.xaml.vbをダブルクリックしてリスト2のコードを記述します。
ロジックコードを記述する
リスト2 (MainPage.xaml.vb)
Option Strict On Imports System.Xml.Linq Imports System.IO 仮想ファイルシステムを作成および使用するための型が含まれている、System.IO.IsolatedStorage名前空間をインポートします。分離ストレージによって、安全なクライアント側のストレージが提供されます。 Imports System.IO.IsolatedStorage Partial Public Class MainPage Inherits PhoneApplicationPage ' コンストラクター Public Sub New() InitializeComponent() End Sub Sharedキーワードでデータの番号となるメンバ変数numberを宣言しておきます。 Shared number As Integer = 1
ページがアクティブになった時呼び出されるメソッド
変数storageを、ファイルとディレクトリを格納している分離ストレージ領域を表すIsolateStorageFileクラスとして宣言します。Path.Combineで、PersonalInfoというフォルダ名と、PersonalInfo.xmlというXMLファイルを連結し、filePath変数に格納しておきます。 FileExistsメソッドでXMLファイルが存在しているかどうかをチェックし、存在している場合は以下の処理を実行します。 [データ一覧]ボタンの使用を可能にします。IsolatedStorageFileクラスのOpenFileメソッドでPersonalInfoフォルダ内のPersonalInfo.xmlファイルを、指定したファイルアクセスを使用して指定したモードでファイルを開きます。開いたファイルをStreamReaderで読み込みます。ReadToEndメソッドでファイルの最後まで読み取り、変数readXmldoc変数に格納しておきます。読み込んだXMLテキストをParseメソッドでXElementとして読み込みます。<情報>要素の子要素<番号>の値を取得し、変数getNumberに格納します。Integer.Parseメソッドで取得した「番号」を数値に変換し、1を加算し、メンバ変数numberに格納しておきます。PersonalInfoフォルダにPersonalInfo.xmlファイルが存在しない場合は、[データ一覧]ボタンの使用は不可のままです。 noTextBoxにメンバ変数numberの値を文字列に変換して表示します。 後ほど作成する、DataIchiranPage.xamlから渡された文字データを受け取ります。文字データはNavigationContextのQueryStringにDictionaryとして提供されます。ContainsKeyメソッドで指定したキーがDictionaryに格納されているかどうかを判断します。この場合はIndexというキーがDictionaryに格納されているかどうかを判断し、格納されている場合は以下の処理を実行します。 文字データとしてのIndexで渡された値を数値に変換して、変数Indexに格納します。Indexの値が0より小さい場合は処理を抜けます。IsolatedStorageFileクラスのOpenFileメソッドでPersonalInfoフォルダ内のPersonalInfo.xmlファイルを、指定したファイルアクセスを使用して指定したモードでファイルを開きます。開いたファイルをStreamReaderで読み込みます。ReadToEndメソッドでファイルの最後まで読み取り、変数readXmldoc変数に格納しておきます。読み込んだXMLテキストをParseメソッドでXElementとして読み込みます。 変数Indexに該当する<情報>要素の子要素の内容テキストを取得し、各TextBoxのTextプロパティに指定します。データ一覧から選択されたインデックスに該当するデータがTextBoxに表示されます。[保存]ボタンは使用不可となり、[新規]ボタンは使用可能となります。 Protected Overrides Sub OnNavigatedTo(e As System.Windows.Navigation.NavigationEventArgs) Dim Index As Integer Dim storage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication Dim filePath As String = Path.Combine("PersonalInfo", "PersonalInfo.xml") If storage.FileExists(filePath) = True Then ichiranButton.IsEnabled = True Using stream As IsolatedStorageFileStream = storage.OpenFile(filePath, FileMode.Open, FileAccess.Read) Using reader As StreamReader = New StreamReader(stream, System.Text.Encoding.UTF8) Dim readXmldoc As String = reader.ReadToEnd Dim xmldoc As XElement = XElement.Parse(readXmldoc) Dim getNumber As String = xmldoc.Descendants("情報").Elements("番号").Last.Value number = Integer.Parse(getNumber) + 1 End Using End Using Else ichiranButton.IsEnabled = False End If noTextBlock.Text = number.ToString Dim myParam As IDictionary(Of String, String) = NavigationContext.QueryString If myParam.ContainsKey("Index") = True Then Index = Integer.Parse(myParam("Index")) If Index < 0 Then Exit Sub Using myStream As IsolatedStorageFileStream = storage.OpenFile(filePath, FileMode.Open, FileAccess.Read) Using reader As StreamReader = New StreamReader(myStream, System.Text.Encoding.UTF8) Dim readXmldoc As String = reader.ReadToEnd Dim doc As XElement = XElement.Parse(readXmldoc) noTextBlock.Text = doc.Descendants("情報")(Index).Element("番号").Value nameTextBox.Text = doc.Descendants("情報")(Index).Element("氏名").Value addressTextBox.Text = doc.Descendants("情報")(Index).Element("住所").Value telTextBox.Text = doc.Descendants("情報")(Index).Element("電話").Value mailTextBox.Text = doc.Descendants("情報")(Index).Element("E-mail").Value saveButton1.IsEnabled = False newButton.IsEnabled = True End Using End Using End If MyBase.OnNavigatedTo(e) End Sub
[保存]ボタンがタップされた時の処理
変数storageを、ファイルとディレクトリを格納している分離ストレージ領域を表すIsolateStorageFileクラスとして宣言します。DirectryExistsメソッドでPersonalInfoというフォルダが存在しているかどうかをチェックし、存在していない場合は、CreateDirectoryメソッドでPersonalInfoというフォルダを作成します。 Path.CombineでPersonalInfoというフォルダとPersonalInfo.xmlファイルとを連結します。PeronalInfoフォルダ内にPersonalInfo.xmlが存在しない場合、つまり、1番目のデータが入力されてPersonalInfo.xmlファイルとして保存される場合の処理です。 Visual Basic の埋め込み式を用いて、XML宣言とルート要素<個人情報>、その子要素として<情報>、<情報>要素の子要素として、<番号>、<氏名>、<住所>、<電話>、<E-mail>を作成し、内容テキストとして、埋め込み式の構文である <%= expression %>を用いて各TextBoxに入力された値を指定します。これは ASP.NET で使用される構文と同じです。 分離ストレージ内のファイルを表すIsolatedStorageFileStreamクラス用オブジェクト変数streamを用意し、IsolatedStorageFile.CreateFileメソッドで、分離ストレージ内にfilePath変数の持っているフォルダ名付きXMLファイルを作成します。PersonalInfoフォルダ内にPersonalInfo.xmlファイルが存在する場合は、新しいStreamWriter 生成し、IsolatedStorageFile.OpenFileメソッドで、指定したファイルアクセスを使用して指定したモードでファイルを開き、初期化します。Writeメソッドで埋め込み式のXMLをストリームに書き込みます。保存した旨のメッセージを表示します。 次は、既にPersonalInfoフォルダ内にPersonalInfo.xmlが存在する場合の処理です。 分離ストレージ内のファイルを表すIsolatedStorageFileStreamクラス用オブジェクト変数myStreamを用意し、IsolatedStorageFileクラスのOpenFileメソッドでPersonalInfoフォルダ内のPersonalInfo.xmlファイルを、指定したファイルアクセスを使用して指定したモードでファイルを開きます。開いたファイルをStreamReaderで読み込みます。ReadToEndメソッドでファイルの最後まで読み取り変数readXmldoc変数に格納しておきます。読み込んだXMLテキストをParseメソッドでXElementとして読み込みます。 追加する<情報>要素とその子要素を、埋め込み式を用いて生成し、各要素の値に各TextBoxに入力された値を指定します。新しく生成したXML要素を、読み込んだXMLにAddメソッドで追加します。IsolatedStorageFileStreamを閉じます。 PersonalInfo.xmlファイルが存在する場合は、新しいStreamWriter 生成し、IsolatedStorageFile.OpenFileメソッドで、指定したファイルアクセスを使用して指定したモードでファイルを開き、初期化します。Writeメソッドで、新しいXML要素の追加されたXMLをストリームに書き込みます。保存した旨のメッセージを表示します。 入力ボックス内を空にするDataClearプロシジャを実行します。メンバ変数numberを1つ加算します。加算したnumber変数の値を文字列に変換して、noTextBlockに表示します。 Private Sub saveButton1_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles saveButton1.Click Dim storage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication If storage.DirectoryExists("PersonalInfo") = False Then storage.CreateDirectory("PersonalInfo") End If Dim filePath As String = Path.Combine("PersonalInfo", "PersonalInfo.xml") If storage.FileExists(filePath) = False Then Dim xmldoc As XDocument = <?xml version="1.0" encoding="utf-8"?> <個人情報> <情報> <番号><%= noTextBlock.Text %></番号> <氏名><%= nameTextBox.Text %></氏名> <住所><%= addressTextBox.Text %></住所> <電話><%= telTextBox.Text %></電話> <E-mail><%= mailTextBox.Text %></E-mail> </情報> </個人情報> Using stream As IsolatedStorageFileStream = storage.CreateFile(filePath) End Using If storage.FileExists(filePath) = True Then Using writer As StreamWriter = New StreamWriter(storage.OpenFile(filePath, FileMode.Open, FileAccess.Write)) writer.Flush() writer.Write(xmldoc.ToString) MessageBox.Show("保存しました。") ichiranButton.IsEnabled = True End Using End If Else Dim myStream As IsolatedStorageFileStream = storage.OpenFile(filePath, FileMode.Open, FileAccess.Read) Using reader As StreamReader = New StreamReader(myStream, System.Text.Encoding.UTF8) Dim readXmldoc As String = reader.ReadToEnd Dim doc As XElement = XElement.Parse(readXmldoc) Dim addXml As XElement = <情報> <番号><%= noTextBlock.Text %></番号> <氏名><%= nameTextBox.Text %></氏名> <住所><%= addressTextBox.Text %></住所> <電話><%= telTextBox.Text %></電話> <E-mail><%= mailTextBox.Text %></E-mail> </情報> doc.Add(addXml) myStream.Close() If storage.FileExists(filePath) = True Then Using writer As StreamWriter = New StreamWriter(storage.OpenFile(filePath, FileMode.Open, FileAccess.Write)) writer.Flush() writer.Write(doc.ToString) MessageBox.Show("保存しました。") End Using End If End Using End If DataClear() number = number + 1 noTextBlock.Text = number.ToString End Sub
全てのTextBox内を空にして、次のデータが入力できるようにするプロシージャ
Private Sub DataClear() nameTextBox.Text = String.Empty addressTextBox.Text = String.Empty telTextBox.Text = String.Empty mailTextBox.Text = String.Empty End Sub
[データ一覧]ボタンがタップされた時の処理
これから作成する、DataIchiranPage.xamlに遷移します。 Private Sub ichiranButton_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles ichiranButton.Click NavigationService.Navigate(New Uri("/DataIchiranPage.xaml", UriKind.Relative)) End Sub
[キャンセル]ボタンがタップされた時の処理
DataClearプロシージャを実行します。 Private Sub cancelButton_Click(sender As Object, e As System.Windows.RoutedEventArgs) Handles cancelButton.Click DataClear() End Sub
[新規]ボタンがタップされた時の処理
自分自身のページに遷移します。 Private Sub newButton_Click(sender As System.Object, e As System.Windows.RoutedEventArgs) Handles newButton.Click NavigationService.Navigate(New Uri("/MainPage.xaml", UriKind.Relative)) End Sub End Class
「Windows Phone 縦向きのページ」(DataIchiranPage.xaml)の作成
VS2010メニューの「プロジェクト(P)/新しい項目の追加(W)」と選択し、「Windows Phone 縦向きのページ」を選択します。「名前(N)」にはDataIchiranPage.xamlと入力します。
DataIchiranPage.xamlの編集とコントロールの配置
x:NameがPageTitleというTextBlockのTextプロパティに「データの一覧」と指定します。x:NameがApplicationTitleというTextBlockのTextプロパティに「個人情報」と指定します。ツールボックスからListBoxコントロールを1個配置します(図4)。
図4:ListBoxコントロールを配置した(クリックで拡大) |
書き出されるXAMLコードは省略します。
次に、DataIchiranPage.xamlを展開して表示される、DataIchiranPage.xaml.vbをダブルクリックしてリスト3のコードを記述します。
ロジックコードを記述する
リスト3 (DataIchiranPage.xaml.vb)
Option Strict On Imports System.Xml.Linq Imports System.IO Imports System.IO.IsolatedStorage Partial Public Class DataIchiranPage Inherits PhoneApplicationPage Public Sub New() InitializeComponent() End Sub
ページがアクティブになった時呼び出されるメソッド
変数storageを、ファイルとディレクトリを格納している分離ストレージ領域を表すIsolateStorageFileクラスとして宣言します。Path.CombineでPersonalInfoというフォルダとPersonalInfo.xmlというXMLファイル名と連結します。 分離ストレージ内のファイルを表すIsolatedStorageFileStreamクラス用オブジェクト変数myStreamを用意し、IsolatedStorageFileクラスのOpenFileメソッドでPersonalInfoフォルダ内のPersonalInfo.xmlファイルを、指定したファイルアクセスを使用して指定したモードでファイルを開きます。開いたファイルをStreamReaderで読み込みます。ReadToEndメソッドでファイルの最後まで読み取り変数readXmldoc変数に格納しておきます。 読み込んだXMLテキストをParseメソッドでXElementとして読み込みます。文字列型の新しいリストであるnameListオブジェクトを作成します。 Descendantsメソッドで、子孫要素である全ての <情報> 要素のコレクションを選択し、各要素を、変数resultに格納しながら、以下の処理を繰り返します。 nameListオブジェクトにAddメソッドで、<情報>要素の子要素<氏名>の値を追加していきます。ListBoxのItemsSourceプロパティに「氏名」の追加されたnameListオブジェクトを指定します。これで、ListBoxに氏名の一覧が表示されます。 Protected Overrides Sub OnNavigatedTo(e As System.Windows.Navigation.NavigationEventArgs) Dim storage As IsolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication Dim filePath As String = Path.Combine("PersonalInfo", "PersonalInfo.xml") Using myStream As IsolatedStorageFileStream = storage.OpenFile(filePath, FileMode.Open, FileAccess.Read) Using reader As StreamReader = New StreamReader(myStream, System.Text.Encoding.UTF8) Dim readXmldoc As String = reader.ReadToEnd Dim doc As XElement = XElement.Parse(readXmldoc) Dim nameList As New List(Of String) For Each result In From c In doc.Descendants("情報") Select c nameList.Add(result.Element("氏名").Value) Next ListBox1.ItemsSource = nameList End Using End Using MyBase.OnNavigatedTo(e) End Sub
ListBoxから任意の氏名が選択された時の処理
選択された項目のインデックス番号を引数にして、MainPage.xamlに遷移します。 Private Sub ListBox1_SelectionChanged(sender As Object, e As System.Windows.Controls.SelectionChangedEventArgs) Handles ListBox1.SelectionChanged NavigationService.Navigate(New Uri(String.Format("/MainPage.xaml?Index={0}", ListBox1.SelectedIndex.ToString), UriKind.Relative)) End Sub End Class
入力したデータを分離ストレージに保存し、一覧で表示する