一步一步学习Silverlight
———数据与通信
概述:
由TerryLee编写的《Silverlight 2完美征程》一书,已经上市,在该系列文章的基础上补充了大量的内容,敬请关注。官方网站:http://www.dotneteye.cn/silverlight
Silverlight 2 Beta 1版本发布了,无论从Runtime还是Tools都给我们带来了很多的惊喜,如支持框架语言Visual Basic, Visual C#, IronRuby, Ironpython,对JSON、Web Service、WCF以及Sockets的支持等一系列新的特性。《一步一步学Silverlight 2系列》文章将从Silverlight 2基础知识、数据与通信、自定义控件、动画、图形图像等几个方面带您快速进入Silverlight 2开发。
(一)数据与通信之WebClient
本文将介绍如何在Silverlight 2中使用Web Client进行通信。
简单示例
编写一个简单的示例,在该示例中,选择一本书籍之后,我们通过Web Client去查询书籍的价格,并显示出来,最终的效果如下:
编写界面布局,XAML如下:
为了模拟查询价格,我们编写一个HttpHandler,接收书籍的No,并返回价格: public class BookHandler : IHttpHandler { public static readonly string[] PriceList = new string[] { \, \, \, \, \ }; public void ProcessRequest(HttpContext context) { context.Response.ContentType = \; context.Response.Write(PriceList[Int32.Parse(context.Request.QueryString[\])]); } public bool IsReusable { get { return false; } } } 在界面加载时绑定书籍列表,关于数据绑定可以参考一步一步学Silverlight 2系列(11):数据绑定。 void UserControl_Loaded(object sender, RoutedEventArgs e) { List books = new List() { new Book(\), new Book(\), new Book(\), new Book(\), new Book(\) }; Books.ItemsSource = books; } 接下来当用户选择一本书籍时,需要通过Web Client去获取书籍的价格,在Silverlight 2中,所有的网络通信API都设计为了异步模式。在声明一个Web Client实例后,我们需要为它注册DownloadStringCompleted事件处理方法,在下载完成后将会被回调,然后再调用DownloadStringAsync方法开始下载。
void Books_SelectionChanged(object sender, SelectionChangedEventArgs e) { Uri endpoint = new Uri(String.Format(\,Books.SelectedIndex)); WebClient client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); client.DownloadStringAsync(endpoint); } void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error == null) { lblPrice.Text = \价格:\+ e.Result; } else { lblPrice.Text = e.Error.Message; } } 注意大家可以在Web Application Project的属性页中,把ASP.NET Development Server的端口号设置为一个固定的端口号:
最后完整的代码如下:
public partial class Page : UserControl { public Page() { InitializeComponent(); } void UserControl_Loaded(object sender, RoutedEventArgs e) { List books = new List() { new Book(\), new Book(\), new Book(\), new Book(\), new Book(\) }; Books.ItemsSource = books; } void Books_SelectionChanged(object sender, SelectionChangedEventArgs e) { Uri endpoint = new Uri(String.Format(\,Books.SelectedIndex)); WebClient client = new WebClient(); client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); client.DownloadStringAsync(endpoint); } void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) { if (e.Error == null) { lblPrice.Text = \价格:\+ e.Result; } else { lblPrice.Text = e.Error.Message; } } }