构建天气查看器应用:Silverlight、XML与Web服务的实践之旅
1. 学习目标与平台概述
1.1 学习目标
在本次学习中,我们将掌握以下技能:
- 使用Silverlight创建丰富的互联网应用程序。
- 在XAML中创建Silverlight用户界面。
- 运用LINQ to XML将XML转换为Visual Basic对象集合。
- 利用XML轴属性在Visual Basic中操作XML内容。
- 自定义现有Silverlight控件的外观。
- 创建自定义Silverlight控件。
1.2 平台概述
Silverlight是微软用于富互联网应用程序(RIAs)的平台,其前身代码名为“Windows Presentation Foundation Everywhere (WPF/E)”。它能提供类似桌面应用程序的响应能力和丰富的GUI功能,旨在补充如Adobe Flash和Flex、Sun的JavaFX以及微软自己的ASP.NET Ajax等RIA技术。
Silverlight目前作为浏览器插件,可在近期版本的Microsoft Windows和Mac OS X的Internet Explorer、Firefox和Safari浏览器中运行,也可通过Mono Project的Moonlight在Linux系统上使用。
1.2.1 Silverlight 1.0
主要专注于媒体,仅支持JavaScript编程。其主要目的是利用基于网络的视频日益普及的趋势来推动用户采用,因为用户通常愿意安装软件来观看视频。微软还提供了Silverlight Streaming服务,允许用户免费分发基于媒体的Silverlight应用程序。
1.2.2 Silverlight 2
是.NET平台的一个强大的跨平台、跨浏览器子集,作为插件(约4兆字节下载量)在Windows和Mac OS X上的多个流行浏览器中运行,也可通过Moonlight在Linux系统上使用。当Silverlight 2发布时,运行Silverlight 1.0浏览器插件的计算机将自动升级到Silverlight 2。
Silverlight 2包含的.NET Framework子集提供了用于集合、输入/输出、泛型、多线程、全球化、XML和LINQ的API,还包括与JavaScript和网页元素交互的API,以及用于本地存储Web应用程序数据的API。
由于Silverlight 2是.NET平台的实现,开发人员可以使用如Visual Basic、Visual C#、IronRuby和IronPython等.NET语言创建Silverlight应用程序,这使得熟悉Windows .NET编程的开发人员能够轻松创建在Web浏览器中运行的应用程序,并且相比Silverlight 1.0有显著的性能提升。
1.2.3 图形和GUI功能
Silverlight 2的图形和GUI功能是Windows Presentation Foundation (WPF)框架的子集,支持GUI控件、布局管理、图形、动画和多媒体,还具备基于样式和模板的换肤功能。以下是Silverlight 2中可用的默认控件列表:
| 控件名称 | 控件名称 |
| — | — |
| Border | Button |
| Calendar | Canvas |
| CheckBox | ContentControl |
| DataGrid | DatePicker |
| Ellipse | Grid |
| GridSplitter | HyperlinkButton |
| Image | Line |
| ListBox | MediaElement |
| MultiScaleImage | RadioButton |
| Rectangle | RepeatButton |
| ScrollBar | ScrollViewer |
| Slider | StackPanel |
| TextBlock | TextBox |
| ToggleButton | ToolTip |
1.2.4 数据绑定
与WPF一样,Silverlight提供了强大的数据绑定模型,便于在GUI中显示来自对象、集合、数据库、XML甚至其他控件的数据。
1.2.5 网络功能
Silverlight 2提供了丰富的网络支持,使开发人员能够编写调用Web服务和使用其他网络技术的基于浏览器的应用程序。
2. 软件安装
要构建和执行示例,需要下载并安装以下软件:
2.1 Silverlight 2 Runtime
可从 www.microsoft.com/silverlight/resources/installationFiles.aspx?v=2.0 下载Silverlight 2 Runtime插件。安装后,可访问 silverlight.net/themes/silverlight/community/gallerydetail.aspx?cat=2 尝试一些示例应用程序。
2.2 Silverlight Tools Beta 1 for Visual Studio 2008
由于目前Microsoft的Visual Studio Express版本尚不支持Silverlight 2开发,因此需要完整版本的Visual Studio 2008。可从 go.microsoft.com/fwlink/?LinkID=112029 下载Silverlight Tools Beta 1 for Visual Studio 2008,下载并执行文件silverlight_chainer.exe,然后按照屏幕上的说明安装用于在Visual Studio 2008中开发Silverlight 2应用程序的工具。
2.3 Silverlight 2 SDK (Software Development Kit) Beta 1
如果无法访问完整版本的Visual Studio 2008,可从 go.microsoft.com/fwlink/?LinkID=111096&clcid=0x409 获取Silverlight 2 SDK Beta 1。该SDK提供了文档、示例代码和工具,帮助开发人员为Silverlight 2测试版构建应用程序。
3. 测试驱动天气查看器应用程序
3.1 应用程序要求
需要创建一个基于Web的应用程序,允许用户输入美国邮政编码,并显示相应城市的天气预报。为获取天气预报,必须使用 www.webservicex.net 提供的GetWeatherByZipCode Web服务。应用程序应显示Web服务返回的星期几以及代表每天天气的图像,用户可以点击相应的日期查看该天的华氏和摄氏高低温度。
3.2 测试步骤
- 打开完成的应用程序 :打开目录
C:\Examples\Tutorial32\CompletedApplication\WeatherViewer,找到Weather Viewer应用程序,双击WeatherViewer.sln在Visual Studio IDE中打开该应用程序。 - 运行应用程序 :选择“Debug > Start Without Debugging”或按“Ctrl + F5”运行应用程序。
- 输入美国邮政编码 :在TextBox中输入美国邮政编码,然后按下“Get Weather”按钮以获取指定邮政编码的天气预报。可在 zip4.usps.com/zip4/ 找到美国邮政编码列表。
- 显示预报详情 :点击预报中的某一天,查看该天的完整详情。注意,必须点击“Close”按钮才能返回预报界面。
- 关闭应用程序 :点击浏览器的关闭框关闭正在运行的应用程序。
- 关闭IDE :点击IDE的关闭框关闭IDE。
以下是天气查看器应用程序的操作流程mermaid图:
graph LR
A[打开应用程序] --> B[运行应用程序]
B --> C[输入邮政编码]
C --> D[获取天气预报]
D --> E[选择日期查看详情]
E --> F[关闭详情界面]
F --> G[关闭应用程序]
G --> H[关闭IDE]
4. 天气查看器应用程序概述
4.1 伪代码描述
以下伪代码描述了应用程序的基本操作:
当用户按下“Get Weather”按钮时:
从TextBox中获取美国邮政编码
使用WebClient对象调用来自www.webservicex.net的WeatherForecast Web服务
当从Web服务接收到响应数据时:
将XML天气预报转换为WeatherData对象
使用数据绑定在ListBox中显示Weather Data对象
当用户选择天气预报中的某一天时:
显示该天的完整预报详情
当用户在详情视图中点击“Close”按钮时:
关闭详情视图
当用户更改TextBox中的文本时:
清除ListBox的内容
4.2 ACE表
为了将伪代码转换为Visual Basic,可使用以下ACE表:
| 操作 | 控件/对象/类 | 事件 |
| — | — | — |
| 提交按钮点击 | submitButton | Click |
| 从TextBox获取邮政编码 | inputTextBox | |
| 使用WebClient对象调用GetWeatherByZipCode Web服务 | weatherService | DownloadStringCompleted |
| 将XML天气预报转换为WeatherData对象 | XDocument, WeatherData | |
| 使用数据绑定在ListBox中显示Weather Data对象 | forecastList | SelectionChanged |
| 显示某一天的完整预报详情 | forecastList, completeDetails | |
| 关闭详情视图 | closeButton | Click |
| 清除ListBox的内容 | inputTextBox | TextChanged |
5. 创建天气查看器应用程序
5.1 创建Silverlight应用程序项目
- 在Visual Studio中,选择“File > New Project…”以显示“New Project”对话框。
- 在对话框中,在Visual Basic Silverlight项目类型下,选择“Silverlight Application”并将项目命名为“WeatherViewer”,然后点击“OK”。
5.2 添加测试网站
在点击“OK”后出现的“Add Silverlight Application”对话框中,选择“Add a new Web to the solution for hosting the control”单选按钮,并从“Project Type ComboBox”中选择“Web Application Project”。点击“OK”以创建Silverlight应用程序。
5.3 Silverlight应用程序项目基础
基本的Silverlight应用程序有两个XAML文件:Page.xaml和App.xaml。Page.xaml定义应用程序的GUI,其代码隐藏文件Page.xaml.vb声明GUI事件处理程序和其他所需方法;App.xaml声明应用程序的共享资源,如可应用于各种GUI元素的样式,其代码隐藏文件App.xaml.vb定义应用程序级别的事件处理程序。
5.4 布局和构建GUI
Silverlight提供了三种类型的布局容器:Canvas、StackPanel和Grid。
- Canvas :可精确控制每个控件的位置,当Canvas调整大小时,其上的控件不会移动。
- StackPanel :可水平或垂直(默认)放置一组控件,常用于组织GUI的子集。
- Grid :是Silverlight中最灵活的布局面板,可指定行和列,并将每个控件放置在Grid中的特定行和列中,控件还可以跨越多行或多列,行和列可以有固定大小或自动调整大小。
以下是使用Grids定义布局的具体步骤:
5.4.1 更改背景颜色并显示网格线
将Grid的背景颜色更改为LightSkyBlue,可通过删除第5行Background属性中的White,然后按“Ctrl + Space”显示包含预定义颜色名称的IntelliSense窗口,从中选择一个值,也可以指定十六进制颜色值。在右尖括号(>)前按“Enter”并插入ShowGridLines属性,以显示网格线,方便设计和构建GUI。
5.4.2 定义主Grid中的行和列
默认情况下,Grid包含一行一列,我们将其拆分为两行一列。插入以下代码:
<Grid.RowDefinitions>
<RowDefinition Height="35" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
</Grid.ColumnDefinitions>
5.4.3 创建另一个Grid放置在主Grid的第一行
第一行包含三个元素,使用Grid指定该行中每个控件的宽度。插入以下代码:
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="35" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="110" />
<ColumnDefinition Width="110" />
</Grid.ColumnDefinitions>
</Grid>
5.4.4 在GUI的第一行插入控件
插入以下代码以创建GUI的第一行:
<Border Grid.Row="0" Grid.Column="0" CornerRadius="10" Background="LightGray" Margin="2">
<TextBlock Text="Weather Viewer" Padding="6" />
</Border>
<TextBox x:Name="inputTextBox" Grid.Row="0" Grid.Column="1" FontSize="18" Margin="4" />
<Button x:Name="submitButton" Grid.Row="0" Grid.Column="2" Content="Get Weather" Margin="4" />
5.4.5 在主Grid的第二行放置TextBlock
添加以下代码以在主Grid的第二行显示TextBlock:
<TextBlock Grid.Row="1" Text="Second row placeholder" />
5.4.6 运行应用程序
选择“Debug > Start Debugging”运行应用程序,尝试调整浏览器窗口大小,会发现应用程序不会自动调整大小。如果出现“Debugging Not Enabled”对话框,保持第一个单选按钮选中并点击“OK”以启用调试。
5.4.7 使应用程序在浏览器窗口中可调整大小
移除第4行的Width和Height属性,并将右尖括号(>)移到第3行的末尾。当不指定Width和Height时,Silverlight应用程序将占据整个浏览器窗口,再次运行应用程序以确认其现在可调整大小。
6. 调用Web服务并使用LINQ to XML处理结果
6.1 调用Web服务
在Silverlight应用程序中调用Web服务,需要使用 WebClient 对象。以下是调用 GetWeatherByZipCode Web服务的基本步骤:
1. 创建 WebClient 对象。
2. 注册 DownloadStringCompleted 事件处理程序。
3. 使用 DownloadStringAsync 方法调用Web服务。
示例代码如下:
Dim webClient As New WebClient()
AddHandler webClient.DownloadStringCompleted, AddressOf WeatherService_DownloadStringCompleted
webClient.DownloadStringAsync(New Uri("http://www.webservicex.net/GetWeatherByZipCode?zipcode=" & zipCode))
6.2 处理XML响应
当从Web服务接收到响应数据后,需要将XML天气预报转换为 WeatherData 对象。可以使用LINQ to XML来完成这个任务。以下是处理XML响应的示例代码:
Private Sub WeatherService_DownloadStringCompleted(sender As Object, e As DownloadStringCompletedEventArgs)
If e.Error Is Nothing Then
Dim xmlDoc As XDocument = XDocument.Parse(e.Result)
Dim weatherDataList As New List(Of WeatherData)()
For Each weatherNode In xmlDoc.Descendants("WeatherData")
Dim weatherData As New WeatherData()
weatherData.Day = weatherNode.Element("Day").Value
weatherData.Temperature = weatherNode.Element("Temperature").Value
weatherDataList.Add(weatherData)
Next
' 使用数据绑定在DataGrid中显示Weather Data对象
forecastDataGrid.ItemsSource = weatherDataList
End If
End Sub
6.3 显示天气数据
使用数据绑定将 WeatherData 对象显示在Silverlight DataGrid 控件中。在XAML中定义 DataGrid :
<DataGrid x:Name="forecastDataGrid" AutoGenerateColumns="True" />
7. 自定义数据展示
7.1 自定义ListBox
为了更美观地显示天气预报,可以将部分天气预报显示在自定义的 ListBox 中,使其元素水平排列。以下是自定义 ListBox 的步骤:
1. 创建一个新的 ListBox 。
2. 设置 ListBox 的 ItemsPanel 属性为 StackPanel ,并将 Orientation 设置为 Horizontal 。
示例代码如下:
<ListBox x:Name="forecastListBox">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
7.2 绑定数据
将 WeatherData 对象绑定到自定义的 ListBox 中:
forecastListBox.ItemsSource = weatherDataList
8. 创建自定义Silverlight控件
8.1 自定义控件需求
创建一个自定义的Silverlight控件,用于显示某一天的详细天气预报,并在用户点击关闭按钮时关闭详情视图。
8.2 创建自定义控件步骤
- 创建一个新的
UserControl。 - 在
UserControl的XAML中定义控件的布局和样式。 - 在
UserControl的代码隐藏文件中处理事件。
以下是自定义控件的XAML示例:
<UserControl x:Class="CustomWeatherDetailControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="400" Height="300">
<Grid Background="LightBlue">
<TextBlock x:Name="dayTextBlock" Text="{Binding Day}" FontSize="24" Margin="10" />
<TextBlock x:Name="temperatureTextBlock" Text="{Binding Temperature}" FontSize="18" Margin="10,40,10,10" />
<Button x:Name="closeButton" Content="Close" HorizontalAlignment="Right" VerticalAlignment="Bottom" Margin="10" Click="closeButton_Click" />
</Grid>
</UserControl>
以下是自定义控件的代码隐藏文件示例:
Public Class CustomWeatherDetailControl
Public Property WeatherData As WeatherData
Get
Return CType(DataContext, WeatherData)
End Get
Set(value As WeatherData)
DataContext = value
End Set
End Property
Private Sub closeButton_Click(sender As Object, e As RoutedEventArgs)
' 关闭详情视图的逻辑
End Sub
End Class
8.3 使用自定义控件
在主应用程序中使用自定义控件:
<local:CustomWeatherDetailControl x:Name="completeDetails" Visibility="Collapsed" />
' 显示详情视图
completeDetails.Visibility = Visibility.Visible
completeDetails.WeatherData = selectedWeatherData
9. 最终天气查看器应用程序代码
将前面各步骤的代码整合起来,形成最终的天气查看器应用程序代码。以下是一个简化的整合示例:
9.1 Page.xaml
<UserControl x:Class="WeatherViewer.Page"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:WeatherViewer">
<Grid Background="LightSkyBlue">
<Grid.RowDefinitions>
<RowDefinition Height="35" />
<RowDefinition Height="*" />
</Grid.RowDefinitions>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="35" />
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="110" />
<ColumnDefinition Width="110" />
</Grid.ColumnDefinitions>
<Border Grid.Row="0" Grid.Column="0" CornerRadius="10" Background="LightGray" Margin="2">
<TextBlock Text="Weather Viewer" Padding="6" />
</Border>
<TextBox x:Name="inputTextBox" Grid.Row="0" Grid.Column="1" FontSize="18" Margin="4" TextChanged="inputTextBox_TextChanged" />
<Button x:Name="submitButton" Grid.Row="0" Grid.Column="2" Content="Get Weather" Margin="4" Click="submitButton_Click" />
</Grid>
<ListBox x:Name="forecastListBox" Grid.Row="1" SelectionChanged="forecastListBox_SelectionChanged">
<ListBox.ItemsPanel>
<ItemsPanelTemplate>
<StackPanel Orientation="Horizontal" />
</ItemsPanelTemplate>
</ListBox.ItemsPanel>
</ListBox>
<local:CustomWeatherDetailControl x:Name="completeDetails" Visibility="Collapsed" />
</Grid>
</UserControl>
9.2 Page.xaml.vb
Imports System.Net
Imports System.Xml.Linq
Imports System.Collections.ObjectModel
Public Class Page
Private Sub submitButton_Click(sender As Object, e As RoutedEventArgs)
Dim zipCode As String = inputTextBox.Text
Dim webClient As New WebClient()
AddHandler webClient.DownloadStringCompleted, AddressOf WeatherService_DownloadStringCompleted
webClient.DownloadStringAsync(New Uri("http://www.webservicex.net/GetWeatherByZipCode?zipcode=" & zipCode))
End Sub
Private Sub WeatherService_DownloadStringCompleted(sender As Object, e As DownloadStringCompletedEventArgs)
If e.Error Is Nothing Then
Dim xmlDoc As XDocument = XDocument.Parse(e.Result)
Dim weatherDataList As New ObservableCollection(Of WeatherData)()
For Each weatherNode In xmlDoc.Descendants("WeatherData")
Dim weatherData As New WeatherData()
weatherData.Day = weatherNode.Element("Day").Value
weatherData.Temperature = weatherNode.Element("Temperature").Value
weatherDataList.Add(weatherData)
Next
forecastListBox.ItemsSource = weatherDataList
End If
End Sub
Private Sub forecastListBox_SelectionChanged(sender As Object, e As SelectionChangedEventArgs)
Dim selectedWeatherData As WeatherData = CType(forecastListBox.SelectedItem, WeatherData)
If selectedWeatherData IsNot Nothing Then
completeDetails.Visibility = Visibility.Visible
completeDetails.WeatherData = selectedWeatherData
End If
End Sub
Private Sub closeButton_Click(sender As Object, e As RoutedEventArgs)
completeDetails.Visibility = Visibility.Collapsed
End Sub
Private Sub inputTextBox_TextChanged(sender As Object, e As TextChangedEventArgs)
forecastListBox.ItemsSource = Nothing
End Sub
End Class
9.3 WeatherData.vb
Public Class WeatherData
Public Property Day As String
Public Property Temperature As String
End Class
10. 总结
通过本次实践,我们学习了如何使用Silverlight创建丰富的互联网应用程序,包括创建用户界面、调用Web服务、处理XML数据、自定义控件等。以下是整个开发过程的流程图:
graph LR
A[创建Silverlight应用程序] --> B[布局和构建GUI]
B --> C[调用Web服务]
C --> D[处理XML响应]
D --> E[自定义数据展示]
E --> F[创建自定义控件]
F --> G[整合代码形成最终应用程序]
在开发过程中,我们使用了多种技术和工具,如XAML、LINQ to XML、WebClient等。通过合理运用这些技术和工具,我们成功地实现了一个功能丰富的天气查看器应用程序。希望本次实践能为你在开发类似应用程序时提供参考和帮助。
Silverlight天气应用查看器实战
超级会员免费看
11万+

被折叠的 条评论
为什么被折叠?



