前回:http://d.hatena.ne.jp/okazuki/20091017/1255761209
前回は、簡単なHello worldを作成しました。
その際に、サーバーサイドの結果を受け取るのにコールバックを使用しました。
今回は、コールバックを使用しない方法でデータを取得してみようと思います。
ということで、サーバーサイドの処理はそのままで、クライアントサイドの処理を書き換えます。
.NET RIA Servicesが自動生成する、クライアントサイドのコードには、読み込み系の処理の戻り値型のコレクションを返すプロパティが定義されています。
今回作ったサンプルでは、Messagesプロパティがそれにあたります。
このMessagesプロパティはGetMessageQueryの結果が勝手に入ってくれるようなつくりになっているので、ListBoxあたりとバインドすると、素敵な感じになってくれたりします。
ということで、XAMLから修正していきます。
TextBoxをListBoxと置き換えて、ItemTemplateでMessageクラスのTextプロパティを表示するように変更します。
<UserControl x:Class="RIAHelloWorld.MainPage" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:d="http://schemas.microsoft.com/expression/blend/2008" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="d" d:DesignWidth="640" d:DesignHeight="480"> <StackPanel x:Name="LayoutRoot"> <ListBox x:Name="listBox"> <ListBox.ItemTemplate> <DataTemplate> <TextBlock Text="{Binding Text}" /> </DataTemplate> </ListBox.ItemTemplate> </ListBox> <Button Content="GetMessage" Click="GetMessageButton_Click" /> </StackPanel> </UserControl>
お次はコードビハインドです。
using System.Linq; using System.Windows; using System.Windows.Controls; using RIAHelloWorld.Web; namespace RIAHelloWorld { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private void GetMessageButton_Click(object sender, RoutedEventArgs e) { var context = new HelloWorldDomainContext(); // ItemSourceとMessagesを紐付け listBox.ItemsSource = context.Messages; // Messageを取得! var query = context.GetMessageQuery(); context.Load(query); } } }
GetMessageQueryの結果をLoadすると、自動的にMessagesプロパティにサーバーから取得したクラスが追加されます。
なので、ItemsSourceと関連付けておくと、データの取得が終わったタイミングでListBoxに表示されるという寸法です。
単一要素を取得するものでなければ、このパターンでデータを取得するのが楽かもしれません。