`
yiyeqinghuasoon
  • 浏览: 644108 次
文章分类
社区版块
存档分类
最新评论

第12课 数据与通信之WebClient

 
阅读更多

概述

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

简单示例

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

TerryLee_Silverlight2_0059

编写界面布局,XAML如下:

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,并返回价格:

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):数据绑定

void UserControl_Loaded(object sender, RoutedEventArgs e)
{
    ListBook> books = new ListBook>() { 
        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方法开始下载。

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

TerryLee_Silverlight2_0060

最后完整的代码如下:

public partial class Page : UserControl
{
    public Page()
    {
        InitializeComponent();
    }

    void UserControl_Loaded(object sender, RoutedEventArgs e)
    {
        ListBook> books = new ListBook>() { 
            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;
        }
    }
}

运行后效果如下:

TerryLee_Silverlight2_0059

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

TerryLee_Silverlight2_0061

结束语

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

分享到:
评论

相关推荐

    Visual.Basic.2010.&.NET4.高级编程(第6版)-文字版.pdf

    第12章 使用sql server 461 12.1 sql server compact 462 12.1.1 连接sql server compactedition数据库 463 12.1.2 同步数据 466 12.2 sql server内置的xml功能 472 12.3 sql server中的clr集成 474 ...

    C#全能速查宝典

    《C#全能速查宝典》共分为8章,分别介绍了C#语言基础、Windows窗体及常用控件、Windows高级控件、控件公共属性、方法及事件、数据库开发、文件、数据流与注册表、GDI+绘图技术和C#高级编程,共包含562个C#编程中常用...

    【RT-Thread作品秀】基于ART-Pi的多场景智能物联终端-电路方案

    本作品针对这一市场痛点,以ART-Pi开发板和RTT操作系统为基础,从软件接口层构建一个相对统一设备至设备(D2D)与设备至云端(D2C)的小型通信接口,使用多种输入设备与多种输出设备验证其实际效能,为RTT与STM32...

    asp.net技术内幕(1)

    11.4 小结 <br>第12章 操作DataSet <br>12.1 理解DataSet 12.1.1 DataSet的元素 12.1.2 向DataSet添加DataTable 12.1.3 将控件绑定到DataSet 12.2 理解DataTable 12.2.1 通过程序...

    asp.net技术内幕(2)

    11.4 小结 <br>第12章 操作DataSet <br>12.1 理解DataSet 12.1.1 DataSet的元素 12.1.2 向DataSet添加DataTable 12.1.3 将控件绑定到DataSet 12.2 理解DataTable 12.2.1 通过程序...

    asp.net技术内幕(5)

    11.4 小结 <br>第12章 操作DataSet <br>12.1 理解DataSet 12.1.1 DataSet的元素 12.1.2 向DataSet添加DataTable 12.1.3 将控件绑定到DataSet 12.2 理解DataTable 12.2.1 通过程序...

    asp.net技术内幕(4)

    11.4 小结 <br>第12章 操作DataSet <br>12.1 理解DataSet 12.1.1 DataSet的元素 12.1.2 向DataSet添加DataTable 12.1.3 将控件绑定到DataSet 12.2 理解DataTable 12.2.1 通过程序...

Global site tag (gtag.js) - Google Analytics