安装Silverlight

开发Silverlight

一步一步学Silverlight 2系列(25):综合实例之Live Search

概述

Silverlight 2 Beta 1版本发布了,无论从Runtime还是Tools都给我们带来了很多的惊喜,如支持框架语言Visual Basic, Visual C#, IronRuby, Ironpython,对JSON、Web Service、WCF以及Sockets的支持等一系列新的特性。《一步一步学Silverlight 2系列》文章将从Silverlight 2基础知识、数据与通信、自定义控件、动画、图形图像等几个方面带您快速进入Silverlight 2开发。

本节将综合前面几篇介绍与浏览器交互部分内容,做一个综合示例——Live Search

准备知识

在本示例中,我们将通过调用Live Search API,在Silverlight中动态创建DOM结构,将搜索的结果展现出来。在使用Live Search API之前,需要先去Live Search Developer Center申请一个应用程序ID。

TerryLee_Silverlight2_0115

申请完成后应用程序ID大约在10分钟左右生效。关于Live Search API的有关详细信息,请大家参考这里

编写ASMX

直接调用API,返回的信息可能有很多,为了简单起见,我们对返回的结果做一些处理,编写一个SearchResultItem类:

public class SearchResultItem
{
    public string Title { get; set; }

    public string Url { get; set; }

    public string Description { get; set; }
}

添加对Live Search API的Service引用,地址为:http://soap.search.live.com/webservices.asmx?wsdl

TerryLee_Silverlight2_0118

在ASMX中对返回的结果进行一些处理,Silverlight程序最后将直接调用ASMX。在调用Live Search时需要指定应用程序ID以及本地化的信息等,查询的参数将在Silverlight程序中调用时传入。

[WebMethod]
public SearchResultItem[] DoSearch(string query)
{
    MSNSearchPortTypeClient s = new MSNSearchPortTypeClient();
    SearchRequest searchRequest = new SearchRequest();
    int arraySize = 1;
    SourceRequest[] sr = new SourceRequest[arraySize];

    sr[0] = new SourceRequest();
    sr[0].Source = SourceType.Web;

    searchRequest.Query = query;
    searchRequest.Requests = sr;

    searchRequest.AppID = "C0680205851CCC0E38946DB8FF74156C1C826A86";
    searchRequest.CultureInfo = "zh-CN";
    SearchResponse searchResponse;

    searchResponse = s.Search(searchRequest);

    List<SearchResultItem> lists = new List<SearchResultItem>();
    foreach (SourceResponse sourceResponse in searchResponse.Responses)
    {
        Result[] sourceResults = sourceResponse.Results;
        foreach (Result sourceResult in sourceResults)
        {
            SearchResultItem item = new SearchResultItem();
            if ((sourceResult.Title != null) && (sourceResult.Title != String.Empty))
                item.Title = sourceResult.Title;

            if ((sourceResult.Description != null) && (sourceResult.Description != String.Empty))
                item.Description = sourceResult.Description;

            if ((sourceResult.Url != null) && (sourceResult.Url != String.Empty))
                item.Url = sourceResult.Url;

            lists.Add(item);
        }
    }
    return lists.ToArray();
}

测试一下我们的服务是否正常:

TerryLee_Silverlight2_0116

修改测试页

在测试ASPX中,修改Silverlight插件的样式控制,并添加一个div用来显示搜索的结果:

<div  style="height:100%;">
    <asp:Silverlight ID="Xaml1" runat="server" 
        Source="~/ClientBin/TerryLee.SilverlightGoogleSearch.xap"
        Version="2.0" Width="857" Height="140" />
    <div id="result"></div>
</div>

定义几个简单的样式:

<style type="text/css">
    #result
    {
        margin-left:20px;
    }
    .urlstyle
    {
        color:#59990E;
    }
    .itemstyle
    {
        border-bottom:dotted 1px #59990E;
        margin-bottom:20px;
    }
</style>

实现Silverlight程序

编写一个简单的Silverlight界面,使其看起来如图所示:

TerryLee_Silverlight2_0117

XAML声明如下:

<Grid x:Name="LayoutRoot" Background="White">
    <Grid.RowDefinitions>
        <RowDefinition Height="55"></RowDefinition>
        <RowDefinition Height="50"></RowDefinition>
        <RowDefinition Height="35"></RowDefinition>
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"></ColumnDefinition>
    </Grid.ColumnDefinitions>
    
    <Image Source="LiveSearch.png" Grid.Column="0"></Image>
    <StackPanel Grid.Row="1" Orientation="Horizontal">
        <TextBox x:Name="txtQuery" Width="400" Height="35"
                 Margin="50 0 0 0" BorderBrush="#3F7801"></TextBox>
        <Button x:Name="btnSearch" Width="120" Height="35"
                Background="#62A21D" Margin="20 0 0 0"
                Content="Search" FontSize="16" Click="btnSearch_Click"></Button>
    </StackPanel>
    <TextBlock Grid.Row="2" Text="网页搜索结果" Foreground="#59990E"
               FontSize="16" Margin="20 0 0 0"></TextBlock>
</Grid>

在Silverlight项目中添加对于ASMX的引用,并编写“Search”按钮的实现,对于如何调用ASMX,可以参考一步一步学Silverlight 2系列(15):数据与通信之ASMX。动态创建DOM结构,并将结果显示出来:

private void btnSearch_Click(object sender, RoutedEventArgs e)
{
    LiveSearchWebServiceSoapClient client = new LiveSearchWebServiceSoapClient();

    client.DoSearchCompleted += new EventHandler<DoSearchCompletedEventArgs>(client_DoSearchCompleted);
    client.DoSearchAsync(this.txtQuery.Text);
}

void client_DoSearchCompleted(object sender, DoSearchCompletedEventArgs e)
{
    if (e.Error == null)
    {
        SearchResultItem[] results = e.Result as SearchResultItem[];

        HtmlElement result = HtmlPage.Document.GetElementById("result");

        foreach (SearchResultItem item in results)
        {
            HtmlElement itemElement = HtmlPage.Document.CreateElement("div");
            itemElement.CssClass = "itemstyle";

            HtmlElement titleElement = HtmlPage.Document.CreateElement("a");
            titleElement.SetAttribute("href",item.Url);
            titleElement.SetAttribute("innerText",item.Title);

            HtmlElement descriptElement = HtmlPage.Document.CreateElement("div");
            descriptElement.SetAttribute("innerText",item.Description);

            HtmlElement urlElement = HtmlPage.Document.CreateElement("span");
            urlElement.SetAttribute("innerText",item.Url);
            urlElement.CssClass = "urlstyle";

            itemElement.AppendChild(titleElement);
            itemElement.AppendChild(descriptElement);
            itemElement.AppendChild(urlElement);

            result.AppendChild(itemElement);
        }
    }
}

运行看一下效果,查询博客园:

TerryLee_Silverlight2_0119

结束语

本文综合了前面关于浏览器集成以及数据与通信部分的内容,开发了一个综合的示例——Live Search。你可以从这里下载本文示例代码。

Your rating: None Average: 3 (2 votes)

评论

The oakley is a fashion statement in itself and adds an extra zing to your personality. The oakley sunglasses is all about introducing the finest selection of merchandise that combines style and comfort. The discount oakley sunglasses line is more known for its artistic work and elegance in design than anything else. Each piece you see on display is a masterpiece in itself and a reflection of oakley sunglasses online's artwork. This brand fake oakley sunglasses is an ideal choice to buy as the designs are always novel and never go out of style. One can buy authentic cheap oakley sunglasses and accessories from reputed stores that offer a complete range of this brand. You can also buy this oakley line from online stores which makes your shopping more easy from the comfort of your home. So make sure you dress up this season with fashion that's filled with the hottest and latest oakley sunglasses in the market. discount oakley sunglasses is a prime American design house that specializes in a big clothesline. They've already created these oakley sunglasses online with the youthful, fashionable, and hip in head. The range is actually excellent and provides an extended type of fancy and serious fake oakley sunglasses that could be donned to any occasion for that polished everyday look. They have the latest in cheap oakley sunglasses collection and people will discover excellent cheap deals on the products.

designs because you would when you trace on clothes. As brian atwood shoes young their moms bright them now they played dissemble their herve leger bandage dress designs because you would when you trace on clothes. As designer watches young their moms bright them now they played dissemble their cheap omega watches designs because you would when you trace on clothes. As jimmy choo shoes young their moms bright them now they played dissemble their brian atwood designs because you would when you trace on clothes. As louboutin uk young their moms bright them now they played dissemble their christian louboutin high heels

ry fine ten big list of fine work day shuttle, designer handbags professional cleaning usually need five days to complete. And the designer outlet ry fine ten big list of fine work day shuttle, lv handbag professional cleaning usually need five days to complete. And the cheap lv handbags ry fine ten big list of fine work day shuttle, christian louboutin professional cleaning usually need five days to complete. And the christian louboutin ry fine ten big list of fine work day shuttle, christian louboutin online professional cleaning usually need five days to complete. And the louboutin uk online