一步一步学Silverlight :数据与通信之WebClient
注意大家可以在Web Application Project的属性页中,把ASP.NET Development Server的端口号设置为一个固定的端口号:
最后完整的代码如下:
public partial class Page : UserControl { public Page() { InitializeComponent(); } void UserControl_Loaded(object sender, RoutedEventArgs e) { List<Book> books = new List<Book>() { new Book("Professional ASP.NET 3.5"), new Book("ASP.NET AJAX In Action"), new Book("Silverlight In Action"), new Book("ASP.NET 3.5 Unleashed"), new Book("Introducing Microsoft ASP.NET AJAX") }; Books.ItemsSource = books; } void Books_SelectionChanged(object sender, SelectionChangedEventArgs e) { Uri endpoint = new Uri(String.Format("http://localhost:49955/BookHandler.ashx?No={0}",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; } } }
当我们选择其中一本书籍时,将会显示出它的价格:
结束语
本文简单介绍了Silverlight 2中使用Web Client进行通信的知识,在Silverlight 2中,提供的通信API非常丰富,后面将会介绍其他的方式。你可以从这里下载本文示例代码。
[第1页][第2页]