开发学院图形图像Flash 学Silverlight 2系列(12):数据与通信之WebClie... 阅读

学Silverlight 2系列(12):数据与通信之WebClient

 2008-10-03 11:36:09 来源:WEB开发网   
核心提示: void Books_SelectionChanged(object sender, SelectionChangedEventArgs e){Uri endpoint = new Uri(String.Format("http://localhost:49955/BookHan

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;
  }
}

注意大家可以在Web Application Project的属性页中,把ASP.NET Development Server的端口号设置为一个固定的端口号:

学Silverlight 2系列(12):数据与通信之WebClient

最后完整的代码如下:

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系列(12):数据与通信之WebClient

当我们选择其中一本书籍时,将会显示出它的价格:

学Silverlight 2系列(12):数据与通信之WebClient

结束语

本文简单介绍了Silverlight 2中使用Web Client进行通信的知识,在Silverlight 2中,提供的通信API非常丰富,后面将会介绍其他的方式。你可以下载本文示例代码。

上一页  1 2 3 

Tags:Silverlight 系列 数据

编辑录入:爽爽 [复制链接] [打 印]
[]
  • 好
  • 好的评价 如果觉得好,就请您
      0%(0)
  • 差
  • 差的评价 如果觉得差,就请您
      0%(0)
赞助商链接