在AutoCompleteBox组件中集成搜索引擎的功能是十分常见的,这有助于我们更好地与Web进行交互。本文将为大家讲述如何在在AutoCompleteBox组件中集成搜索引擎的搜索建议。
实例:
说明:本实例用的搜索引擎是微软的Bing(必应)
详细的说明在代码中给出。
WebServiceHelper.cs(业务辅助类)文件代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Globalization;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Windows.Browser;
using System.Windows.Controls;
namespace SilverlightClient
{
public static class WebServiceHelper
{
private const string LiveSuggestionsJsonUriFormat = "http://api.search.live.net/qson.aspx?query={0}";
private const string LiveSearchUriFormat = "http://search.live.com/results.aspx?q={0}";
public static bool CanMakeHttpRequests
{
get
{
if (!HtmlPage.IsEnabled)
{
return false;
}
string scheme = HtmlPage.Document.DocumentUri.Scheme ?? string.Empty;
return string.Compare(scheme, "http", StringComparison.OrdinalIgnoreCase) == 0;
}
}
public static Uri CreateWebSearchUri(string searchText)
{
return new Uri(string.Format(CultureInfo.InvariantCulture, LiveSearchUriFormat, HttpUtility.UrlEncode(searchText)));
}
public static Uri CreateWebSearchSuggestionsUri(string searchText)
{
return new Uri(string.Format(CultureInfo.InvariantCulture, LiveSuggestionsJsonUriFormat, HttpUtility.UrlEncode(searchText)));
}
}
}
MainPage.xaml文件代码:
<UserControl
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" xmlns:input="clr-namespace:System.Windows.Controls;assembly=System.Windows.Controls.Input" x:Class="SilverlightClient.MainPage"
d:DesignWidth="320" d:DesignHeight="240">
<Grid x:Name="LayoutRoot" Width="320" Height="240" Background="White">
<TextBlock Height="26" HorizontalAlignment="Left" Margin="8,8,0,0" VerticalAlignment="Top" Width="120" FontSize="16" Text="请输入搜索词:" TextWrapping="Wrap"/>
<input:AutoCompleteBox x:Name="Search" FontSize="14" FilterMode="None" Height="26" Margin="8,55,112,0" VerticalAlignment="Top" Width="200"/>
<Button x:Name="GoSearch" Height="26" HorizontalAlignment="Right" Margin="0,55,34,0" VerticalAlignment="Top" Width="74" Content="Search!" FontSize="13.333"/>
</Grid>
</UserControl>
MainPage.xaml.cs文件代码:
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Json;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Browser;
using System.Windows.Controls;
using System.ComponentModel;
namespace SilverlightClient
{
public partial class MainPage : UserControl
{
public MainPage()
{
InitializeComponent();
//注册事件触发处理
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (WebServiceHelper.CanMakeHttpRequests)//如果能做Http请求
{
//注册AutoCompleteBox组件的下拉框内容正在生成事件触发处理
Search.Populating += Search_Populating;
//建立打开结果窗口的事件委托
Action go = () => HtmlPage.Window.Navigate(WebServiceHelper.CreateWebSearchUri(Search.Text), "_blank");
//注册AutoCompleteBox组件的KeyUp事件触发处理。当按下Enter键时,相当于提交
Search.KeyUp += (s, args) =>
{
if (args.Key == System.Windows.Input.Key.Enter)
{
go();
}
};
//搜素按钮的事件触发处理
GoSearch.Click += (s, args) => go();
}
}
private void Search_Populating(object sender, PopulatingEventArgs e)
{
AutoCompleteBox autoComplete = (AutoCompleteBox)sender;
//等待结果
e.Cancel = true;
//创建一个搜索建议请求
WebClient wc = new WebClient();
wc.DownloadStringCompleted += OnDownloadStringCompleted;
wc.DownloadStringAsync(WebServiceHelper.CreateWebSearchSuggestionsUri(autoComplete.SearchText), autoComplete);
}
private void OnDownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
AutoCompleteBox autoComplete = e.UserState as AutoCompleteBox;
if (autoComplete != null && e.Error == null && !e.Cancelled && !string.IsNullOrEmpty(e.Result))//如果没有出现异常情况的话
{
List<string> data = new List<string>();
try
{
JsonObject jso = ((JsonObject)JsonObject.Parse(e.Result))["SearchSuggestion"] as JsonObject;//创建Json对象
string originalSearchString = jso["Query"];//原始查询字符串
if (originalSearchString == autoComplete.SearchText)
{
foreach (JsonObject suggestion in (JsonArray)jso["Section"])
{
data.Add(suggestion.Values.First());
}
autoComplete.ItemsSource = data;//填充AutoCompleteBox组件的数据源
autoComplete.PopulateComplete();//结束AutoCompleteBox组件的下拉框内容生成
}
}
catch
{
}
}
}
}
}
最终效果图: