文本版|topic 高级搜索
   名人堂 帮助 论坛制度 意见反馈 | 首页 博客 周新贴 招聘 专题 新闻
RSS 底部
 
社区导航: 专家门诊   网络技术   操作系统   数据库   程序设计   系统应用   考试认证   CIO及信息化   站长交流   综合交流   下载基地  51CTO产品服务 设为首页 | 收藏本站
51CTO技术论坛» .Net » 一步一步学Silverlight 2系列(12):数据与通信之WebClient       [ 打印]  [ 订阅]  [ 收藏]  [ 推荐给朋友]   [ 本帖文本页]

论坛跳转:
     
标题: [转载] 一步一步学Silverlight 2系列(12):数据与通信之WebClient  ( 查看:289  回复:0 )   
 
零距离
管理员  点击可查看详细


开坛元老   大富翁   诚信兄弟   金点子奖   管理员专用   十二生肖之猴   狮子座   行业勋章   技术勋章  
帖子 6609
精华 21
无忧币 149774
积分 129728
阅读权限 255
来自 (保密)
注册日期 2005-11-30
最后登录 2008-7-9 离线

[查看资料]  [发短消息]  [Blog
[个人主页]    QQ       
发表于:2008-4-15 15:59   标题:一步一步学Silverlight 2系列(12):数据与通信之WebClient
上一帖 |
【概述】

Silverlight 2 Beta 1版本发布了,无论从Runtime还是Tools都给我们带来了很多的惊喜,如支持框架语言Visual Basic, Visual C#, IronRuby, Ironpython,对JSON、Web Service、WCF以及Sockets的支持等一系列新的特性。《一步一步学Silverlight 2系列》文章带您快速进入Silverlight 2开发。

本文将介绍如何在Silverlight 2中使用Web Client进行通信。

【简单示例】

编写一个简单的示例,在该示例中,选择一本书籍之后,我们通过Web Client去查询书籍的价格,并显示出来,最终的效果如下:



编写界面布局,XAML如下:

QUOTE:
<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>
为了模拟查询价格,我们编写一个HttpHandler,接收书籍的No,并返回价格:

QUOTE:
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;
        }
    }
}
在界面加载时绑定书籍列表,关于数据绑定可以参考一步一步学Silverlight 2系列(11):数据绑定。

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

QUOTE:
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的端口号设置为一个固定的端口号:



最后完整的代码如下:

QUOTE:
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非常丰富,后面将会介绍其他的方式。你可以从这里下载本文示例代码。

附件(查看下载说明): [本文示例代码] TerryLee.SilverlightDemo25.rar (2008-4-15 15:59,大小:20.13 K)
该附件被下载 2 次     您下载该主题帖内所有附件同时将被扣掉2点无忧币  查看分数政策说明




网络工程师到底该不该去考CCIE认证?
2008-4-15 15:591楼
[ 顶部 ]
     
论坛跳转:  

| | |

标记已读 · 删除论坛Cookies · 文本版 · WAP
 
| 诚征版主 | 版主堂 | 意见建议 | 大史记 | 论坛地图
Copyright©2005-2008 51CTO.COM  Powered by Discuz!
本论坛言论纯属发布者个人意见,不代表51CTO网站立场!如有疑义,请与管理员联系。
京ICP备05051492号