一步一步学Silverlight :综合实例之Live Search
[1] 一步一步学Silverlight :综合实例之Live Search
[2] 一步一步学Silverlight :综合实例之Live Search
[3] 一步一步学Silverlight :综合实例之Live Search
[4] 一步一步学Silverlight :综合实例之Live Search
[2] 一步一步学Silverlight :综合实例之Live Search
[3] 一步一步学Silverlight :综合实例之Live Search
[4] 一步一步学Silverlight :综合实例之Live Search
实现Silverlight程序
编写一个简单的Silverlight界面,使其看起来如图所示:
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 :数据与通信之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); } } }
运行看一下效果,查询博客园:
结束语
本文综合了前面关于浏览器集成以及数据与通信部分的内容,开发了一个综合的示例——Live Search。你可以从这里下载本文示例代码。