silverlight4数据与通信之WebClient详解

编写一个简单的示例,在该示例中,选择一本书籍之后,我们通过 Web Client 去查询书籍的价格,并显

示出来,最终的效果如下:

编写界面布局,XAML 如下:

<UserControlx:Class="sample.s12"
xmlns="/winfx/2006/xaml/presentation"
xmlns:x="/winfx/2006/xaml"
xmlns:d="/expression/blend/2008"
xmlns:mc="/uploads/allimg/110118/105200L61-1.png" TITLE="silverlight4数据与通信之WebClient详解" />

然后添加以下代码:

using System;
usingSystem.Collections.Generic;
usingSystem.Linq;
usingSystem.Web;

namespacesample.Web
{

public class BookHandler : IHttpHandler
{
public static readonly string[]PriceList = new string[]{
"66.00",
"78.30",
"56.50",
"28.80",
"77.00"};
public void ProcessRequest(HttpContext context)
{
context.Response.ContentType = "text/plain";
context.Response.Write(PriceList[Int32.Parse(context.Request.QueryString["No"])]);
}

public bool IsReusable
{
get
{
return false;
}
}
}
}

特别注意,如果修改“一般处理程序”的名称,比如默认为Handler1,后修改为BookHandler。就会出现未能创建类型“sample.Web.Handler1”的错误,出现这个错误的原因是修改不完全。

解决方法:右键点击ashx文件,查看标记进行修改即可


新建一个BookClass类

using System;
usingSystem.Net;
usingSystem.Windows;
usingSystem.Windows.Controls;
usingSystem.Windows.Documents;
usingSystem.Windows.Ink;
usingSystem.Windows.Input;
usingSystem.Windows.Media;
usingSystem.Windows.Media.Animation;
usingSystem.Windows.Shapes;

namespacesample
{
public class BookClass
{
private string name;

public BookClass(stringname)
{
this.name= name;
}

public string Name
{
get { return name; }
set { name = value; }
}
}
}

然后在后台代码里面进行绑定

private void UserControl_Loaded(objectsender, RoutedEventArgs e)
{

List<BookClass>books = new List<BookClass>()
{
new BookClass("ProfessionalASP.NET 3.5"),
new BookClass("ASP.NETAJAX In Action"),
new BookClass("SilverlightIn Action"),
new BookClass("ASP.NET3.5 Unleashed"),
new BookClass("IntroducingMicrosoft ASP.NET AJAX")
};

Books.ItemsSource = books;
}

现在就可以看到书名的列表了

然后添加SelectionChanged事件。

接下来当用户选择一本书籍时,需要通过Web Client去获取书籍的价格,在Silverlight中,所有的网络通信API都设计为了异步模式。在声明一个WebClient实例后,我们需要为它注册DownloadStringCompleted事件处理方法,在下载完成后将会被回调,然后再调用DownloadStringAsync方法开始下载。

private void Books_SelectionChanged(objectsender, SelectionChangedEventArgs e)
{
//端口可根据自己的情况随便更改
Uri endpoint = new Uri(String.Format("/uploads/allimg/110118/10520021I-3.png" TITLE="silverlight4数据与通信之WebClient详解" />

然后右键点击测试页--在浏览器中查看。至此,你就可以看到最开始展示的页面效果了,注意打开的页面的地址一定是要localhost开头的(IIS),如果是本地路径,那就无法达到效果。


posted @ 2011-01-21 09:56  web程序人生  阅读(293)  评论(0编辑  收藏  举报