Silverlight 2 series (12): WebClient for data and communication

Source: Internet
Author: User
Overview

The release of Silverlight 2 Beta 1 brings us a lot of surprises from Runtime and Tools, such as supporting the framework languages Visual Basic, Visual C #, IronRuby, Ironpython, A series of new features such as JSON, Web Service, WCF, and Sockets support. The one-step learning Silverlight 2 series article takes you to Silverlight 2 development quickly.

This article describes how to use Web Client for communication in Silverlight 2.

Simple Example

Compile a simple example. In this example, after selecting a book, we use the Web Client to query the book price and display it. The final result is as follows:

Compile the interface layout. The XAML is as follows:

<Grid Background = "# 46461F"> <Grid. rowDefinitions> <RowDefinition Height = "40"> </RowDefinition> <RowDefinition Height = "*"> </RowDefinition> <RowDefinition Height = "40"> </RowDefinition> </ grid. rowDefinitions> <Grid. columnDefinitions> <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 = "Books list "Foreground =" White "HorizontalAlignment =" Left "verticalignment =" 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 = "price: "Foreground =" White "HorizontalAlignment =" Left "verticalignment =" Center "Margin =" 20 0 0 0 "> </TextBlock> </Border> </Grid>

To simulate the query price, we compile an HttpHandler, receive the No of the books, and return the price:

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

Bind the book list when loading the interface. For details about data binding, refer to step by step Silverlight 2 series (11): Data Binding.

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

Next, When you select a book, you need to use the Web Client to get the book price. In Silverlight 2, all network communication APIs are designed as asynchronous mode. After declaring a Web Client instance, we need to register the DownloadStringCompleted event processing method for it. After the download is complete, it will be called back and then call the DownloadStringAsync method to start the download.

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 = "Price:" + e. result;} else {lblPrice. text = e. error. message ;}}

Note that you can set the port number of ASP. NET Development Server to a fixed port number on the properties page of the Web Application Project:

The complete code is as follows:

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 = "Price:" + e. result;} else {lblPrice. text = e. error. message ;}}}

The effect after running is as follows:

When we select one of the books, the price will be displayed:

Conclusion

This article briefly introduces how to use Web Client for communication in Silverlight 2. In Silverlight 2, the communication API is rich, and other methods will be introduced later. You can download the sample code from here.

Next article: Step by Step Silverlight 2 series (13): WebRequest for data and communication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.