silverlight4数据与通信之WebClient详解

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

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

编写界面布局,XAML 如下:

<UserControl x:Class="sample.s12"
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:DesignHeight
="300" d:DesignWidth="400" Loaded="UserControl_Loaded">

<Grid Background="#46461F">
<Grid.RowDefinitions>
<RowDefinition Height="40"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="40"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition></ColumnDefinition>
</Grid.ColumnDefinitions>
<Border Grid.Row="0" Grid.Column="0" CornerRadius="15"
Width
="240" Height="36"
Margin
="20 0 0 0" HorizontalAlignment="Left">
<TextBlock Text="书籍列表" Foreground="White"
HorizontalAlignment
="Left" VerticalAlignment="Center"
Margin
="20 0 0 0"></TextBlock>
</Border>
<ListBox x:Name="Books" Grid.Row="1" Margin="40 10 10 10"
SelectionChanged
="Books_SelectionChanged">
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}" Height="32"></TextBlock>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
<Border Grid.Row="2" Grid.Column="0" CornerRadius="15"
Width
="240" Height="36" Background="Orange"
Margin
="20 0 0 0" HorizontalAlignment="Left">
<TextBlock x:Name="lblPrice" Text="价格:" Foreground="White"
HorizontalAlignment
="Left" VerticalAlignment="Center"
Margin
="20 0 0 0"></TextBlock>
</Border>
</Grid>
</UserControl>

为了模拟查询价格,我们编写一个 HttpHandler,接收书籍的 No,并返回价格:

右键点击Web项目--添加--新建项--一般处理程序(选中Web)--改名为BookHandler--添加

如下图所示:

然后添加以下代码:

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

namespace sample.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;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Ink;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

namespace sample
{
public class BookClass
{
private string name;

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

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

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

 

private void UserControl_Loaded(object sender, RoutedEventArgs e)
{

List
<BookClass> books = new List<BookClass>()
{
new BookClass("Professional ASP.NET 3.5"),
new BookClass("ASP.NET AJAX In Action"),
new BookClass("Silverlight In Action"),
new BookClass("ASP.NET 3.5 Unleashed"),
new BookClass("Introducing Microsoft ASP.NET AJAX")
};

Books.ItemsSource
= books;
}

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

然后添加SelectionChanged事件。

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

private void Books_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//端口可根据自己的情况随便更改
Uri endpoint = new Uri(String.Format("http://localhost:80/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;
}
}

最后,设置好端口号,注意要与厚度代码中的端口号一致


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

 

学习资料来源:http://www.cnblogs.com/Terrylee/archive/2008/03/09/Silverlight2-step-by-step-part12-data-and-Communications-webclient.html

按照此方法步骤,中间有些过程跳跃比较大,所以写此详解,供初学者参考。

原文地址:https://www.cnblogs.com/junyuz/p/1937406.html