Windows Phone 7 网络编程之天气预报应用 上

简介:

天气预报应用是通过异步调用Google天气api(http://www.google.com/ig/api?weather=城市拼音),对其进行xml的数据解析,将其数据简单的展现出在Windows Phone 7的客户端上。

 

 

首页的城市数据绑定类,以及预设好的城市列表

City.cs

 

 
  1. View Code   
  2.  
  3. using System.ComponentModel;  
  4.  
  5. namespace WeatherForecast  
  6. {  
  7.     /// <summary> 
  8.     /// 城市绑定类  
  9.     /// </summary> 
  10.     public class City : INotifyPropertyChanged  
  11.     {  
  12.         private string cityPinyin;//城市拼音  
  13.         private string province;//省份  
  14.         private string cityName;//城市名称  
  15.  
  16.         public string CityPinyin  
  17.         {  
  18.             get  
  19.             {  
  20.                 return cityPinyin;  
  21.             }  
  22.             set  
  23.             {  
  24.                 if (value != cityPinyin)  
  25.                 {  
  26.                     cityPinyin = value;  
  27.                     NotifyPropertyChanged("CityPinyin");  
  28.                 }  
  29.             }  
  30.         }  
  31.  
  32.         public string Province  
  33.         {  
  34.             get  
  35.             {  
  36.                 return province;  
  37.             }  
  38.             set  
  39.             {  
  40.                 if (value != province)  
  41.                 {  
  42.                     province = value;  
  43.                     NotifyPropertyChanged("Province");  
  44.                 }  
  45.             }  
  46.         }  
  47.  
  48.         public string CityName  
  49.         {  
  50.             get  
  51.             {  
  52.                 return cityName;  
  53.             }  
  54.             set  
  55.             {  
  56.                 if (value != cityName)  
  57.                 {  
  58.                     cityName = value;  
  59.                     NotifyPropertyChanged("CityName");  
  60.                 }  
  61.             }  
  62.         }  
  63.  
  64.         public event PropertyChangedEventHandler PropertyChanged;  
  65.  
  66.         /// <summary> 
  67.         /// 构造city类  
  68.         /// </summary> 
  69.         public City(string cityPinyin, string province, string cityName)  
  70.         {  
  71.             CityPinyin = cityPinyin;  
  72.             Province = province;  
  73.             CityName = cityName;  
  74.         }  
  75.  
  76.         /// <summary> 
  77.         ///用于绑定属性值改变触发的事件,动态改变  
  78.         /// </summary> 
  79.         private void NotifyPropertyChanged(string property)  
  80.         {  
  81.             if (PropertyChanged != null)  
  82.             {  
  83.                 PropertyChanged(this, new PropertyChangedEventArgs(property));  
  84.             }  
  85.         }  
  86.     }  

Cities.cs

 

 
  1. View Code   
  2.  
  3. using System.Collections.ObjectModel;  
  4.  
  5. namespace WeatherForecast  
  6. {  
  7.     /// <summary> 
  8.     /// 继承 ObservableCollection<City>用户数据绑定  
  9.     /// </summary> 
  10.     public class Cities : ObservableCollection<City> 
  11.     {  
  12.         public Cities() { }  
  13.         /// <summary> 
  14.         /// 设置默认的绑定城市 利用App类里面定义的静态变量cityList  
  15.         /// </summary> 
  16.         public void LoadDefaultData()  
  17.         {  
  18.             App.cityList.Add(new City("Shenzhen", "广东省", "深圳市"));  
  19.             App.cityList.Add(new City("Beijing", "北京市", "北京市"));  
  20.             App.cityList.Add(new City("Shanghai", "上海市", "上海市"));  
  21.             App.cityList.Add(new City("Guangzhou", "广东省", "广州市"));  
  22.             App.cityList.Add(new City("Yangjiang", "广东省", "阳江市"));  
  23.         }  
  24.     }  

对首页城市列表的绑定需要在app程序启动类里面赋值

App.xaml.cs需要添加获取城市列表的代码

public static Cities cityList;//绑定的城市列表

……

private void Application_Launching(object sender, LaunchingEventArgs e)
{
// 创建城市列表
if ( cityList==null)
{
cityList = new Cities();
cityList.LoadDefaultData();
}
}

首页的界面设计代码

 

 
  1. <phone:PhoneApplicationPage   
  2.     x:Class="WeatherForecast.MainPage" 
  3.     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" 
  4.     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" 
  5.     xmlns:phone="clr-namespace:Microsoft.Phone.Controls;assembly=Microsoft.Phone" 
  6.     xmlns:shell="clr-namespace:Microsoft.Phone.Shell;assembly=Microsoft.Phone" 
  7.     xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
  8.     xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
  9.     mc:Ignorable="d" d:DesignWidth="480" d:DesignHeight="768" 
  10.     FontFamily="{StaticResource PhoneFontFamilyNormal}" 
  11.     FontSize="{StaticResource PhoneFontSizeNormal}" 
  12.     Foreground="{StaticResource PhoneForegroundBrush}" 
  13.     SupportedOrientations="Portrait" Orientation="Portrait" 
  14.     shell:SystemTray.IsVisible="True"> 
  15.     <Grid x:Name="LayoutRoot" Background="Transparent"> 
  16.         <Grid.RowDefinitions> 
  17.             <RowDefinition Height="Auto"/> 
  18.             <RowDefinition Height="*"/> 
  19.         </Grid.RowDefinitions> 
  20.         <StackPanel x:Name="TitlePanel" Grid.Row="0" Margin="12,17,0,28"> 
  21.             <TextBlock x:Name="PageTitle" Text="天气预报" Margin="9,-7,0,0" Style="{StaticResource PhoneTextTitle1Style}"/> 
  22.         </StackPanel> 
  23.         <Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"> 
  24.             <ListBox Height="646" HorizontalAlignment="Left" Margin="6,0,0,0" Name="CityList" VerticalAlignment="Top" Width="474" SelectionChanged="CityList_SelectionChanged"> 
  25.                 <ListBox.ItemTemplate><!--数据绑定--> 
  26.                     <DataTemplate> 
  27.                         <StackPanel x:Name="stackPanelCityList" Orientation="Vertical" > 
  28.                             <TextBlock HorizontalAlignment="Left" Foreground="{StaticResource PhoneForegroundBrush}" FontSize="40" Text="{Binding CityPinyin}"/> 
  29.                             <StackPanel Orientation="Horizontal" HorizontalAlignment="Left"> 
  30.                                 <TextBlock Margin="0,0,10,0" FontSize="25" Text="省份:" Foreground="LightBlue"/> 
  31.                                 <TextBlock Margin="0,0,10,0" FontSize="25" Text="{Binding Province}" Foreground="{StaticResource PhoneForegroundBrush}"/> 
  32.                                 <TextBlock Margin="0,0,10,0" FontSize="25" Text="城市:" Foreground="LightBlue"/> 
  33.                                 <TextBlock Margin="0,0,10,0" FontSize="25" Text="{Binding CityName}" Foreground="{StaticResource PhoneForegroundBrush}"/> 
  34.                             </StackPanel> 
  35.                         </StackPanel> 
  36.                     </DataTemplate> 
  37.                 </ListBox.ItemTemplate> 
  38.             </ListBox> 
  39.         </Grid> 
  40.     </Grid> 
  41. </phone:PhoneApplicationPage> 

 

 
  1. using System;  
  2. using System.Windows.Controls;  
  3. using Microsoft.Phone.Controls;  
  4. using System.Windows.Navigation;  
  5.  
  6. namespace WeatherForecast  
  7. {  
  8.     public partial class MainPage : PhoneApplicationPage  
  9.     {  
  10.         public MainPage()  
  11.         {  
  12.             InitializeComponent();  
  13.             CityList.ItemsSource = App.cityList;//绑定城市列表  
  14.         }  
  15.  
  16.         /// <summary> 
  17.         /// 获取天气预报事件  
  18.         /// </summary> 
  19.         private void CityList_SelectionChanged(object sender, SelectionChangedEventArgs e)  
  20.         {  
  21.             // 如果列被选中  
  22.             if (CityList.SelectedIndex != -1)  
  23.             {  
  24.                 City curCity = (City)CityList.SelectedItem;//获取当前选中的城市的绑定的类  
  25.                 this.NavigationService.Navigate(new Uri("/ForecastPage.xaml?City=" +  
  26.                     curCity.CityPinyin, UriKind.Relative));//跳转向ForecastPage.xaml  并传递参数CityPinyin  接口要用到城市的拼音   
  27.             }  
  28.         }  
  29.  
  30.         /// <summary> 
  31.         /// 跳转到ForecastPage.xaml页面前执行该事件  
  32.         /// </summary> 
  33.         protected override void OnNavigatedFrom(NavigationEventArgs args)  
  34.         {  
  35.             // 清空选中的列  
  36.             CityList.SelectedIndex = -1;  
  37.             CityList.SelectedItem = null;  
  38.         }  
  39.     }  

第二个界面 异步调用Google的天气api,解析xml,然后绑定到客户端

天气预报类

ForecastPeriod.cs

 

 
  1. View Code   
  2.  
  3. using System.ComponentModel;  
  4.  
  5. namespace WeatherForecast  
  6. {  
  7.     /// <summary> 
  8.     /// 天气预报绑定类  
  9.     /// </summary> 
  10.     public class ForecastPeriod : INotifyPropertyChanged  
  11.     {  
  12.         private string day_of_week;//星期  
  13.         private int low;//最低温度  
  14.         private int high;//最高温度  
  15.         private string icon;//图片地址  
  16.         private string condition;//天气情况  
  17.  
  18.         public event PropertyChangedEventHandler PropertyChanged;  
  19.  
  20.         public ForecastPeriod()  
  21.         {  
  22.         }  
  23.  
  24.         public string Day_of_week  
  25.         {  
  26.             get  
  27.             {  
  28.                 return day_of_week;  
  29.             }  
  30.             set  
  31.             {  
  32.                 if (value != day_of_week)  
  33.                 {  
  34.                     this.day_of_week = value;  
  35.                     NotifyPropertyChanged("Day_of_week");  
  36.                 }  
  37.             }  
  38.         }  
  39.  
  40.         public int Low  
  41.         {  
  42.             get  
  43.             {  
  44.                 return low;  
  45.             }  
  46.             set  
  47.             {  
  48.                 if (value != low)  
  49.                 {  
  50.                     this.low = value;  
  51.                     NotifyPropertyChanged("Low");  
  52.                 }  
  53.             }  
  54.         }  
  55.  
  56.         public int High  
  57.         {  
  58.             get  
  59.             {  
  60.                 return high;  
  61.             }  
  62.             set  
  63.             {  
  64.                 if (value != high)  
  65.                 {  
  66.                     this.high = value;  
  67.                     NotifyPropertyChanged("High");  
  68.                 }  
  69.             }  
  70.         }  
  71.  
  72.         public string Icon  
  73.         {  
  74.             get  
  75.             {  
  76.                 return icon;  
  77.             }  
  78.             set  
  79.             {  
  80.                 if (value != icon)  
  81.                 {  
  82.                     this.icon = value;  
  83.                     NotifyPropertyChanged("Icon");  
  84.                 }  
  85.             }  
  86.         }  
  87.  
  88.         public string Condition  
  89.         {  
  90.             get  
  91.             {  
  92.                 return condition;  
  93.             }  
  94.             set  
  95.             {  
  96.                 if (value != condition)  
  97.                 {  
  98.                     this.condition = value;  
  99.                     NotifyPropertyChanged("Condition");  
  100.                 }  
  101.             }  
  102.         }  
  103.  
  104.         private void NotifyPropertyChanged(string property)  
  105.         {  
  106.             if (PropertyChanged != null)  
  107.             {  
  108.                 PropertyChanged(this, new PropertyChangedEventArgs(property));  
  109.             }  
  110.         }  
  111.     }  

天气预报列表类 以及异步调用解析的方法

Forecast.cs

 

 
  1. View Code   
  2.  
  3. using System;  
  4. using System.Net;  
  5. using System.Windows;  
  6. using System.ComponentModel;  
  7. using System.Collections.ObjectModel;  
  8. using System.IO;  
  9. using System.Linq;  
  10. using System.Xml.Linq;  
  11.  
  12.  
  13. namespace WeatherForecast  
  14. {  
  15.     /// <summary> 
  16.     /// 天气类以及处理解析异步请求  
  17.     /// </summary> 
  18.     public class Forecast : INotifyPropertyChanged  
  19.     {  
  20.         // 天气预报的城市  
  21.         private string city;  
  22.         // 天气预报的时间  
  23.         private string forecast_date;  
  24.  
  25.         public event PropertyChangedEventHandler PropertyChanged;  
  26.  
  27.         // 不同时间段的天气预报集合  
  28.         public ObservableCollection<ForecastPeriod> ForecastList  
  29.         {  
  30.             get;  
  31.             set;  
  32.         }  
  33.  
  34.         public String City  
  35.         {  
  36.             get  
  37.             {  
  38.                 return city;  
  39.             }  
  40.             set  
  41.             {  
  42.                 if (value != city)  
  43.                 {  
  44.                     city = value;  
  45.                     NotifyPropertyChanged("City");  
  46.                 }  
  47.             }  
  48.         }  
  49.  
  50.         public String Forecast_date  
  51.         {  
  52.             get  
  53.             {  
  54.                 return forecast_date;  
  55.             }  
  56.             set  
  57.             {  
  58.                 if (value != forecast_date)  
  59.                 {  
  60.                     forecast_date = value;  
  61.                     NotifyPropertyChanged("Forecast_date");  
  62.                 }  
  63.             }  
  64.         }  
  65.  
  66.         public Forecast()  
  67.         {  
  68.             ForecastList = new ObservableCollection<ForecastPeriod>();  
  69.         }  
  70.  
  71.         private void NotifyPropertyChanged(string property)  
  72.         {  
  73.             if (PropertyChanged != null)  
  74.             {  
  75.                 PropertyChanged(this, new PropertyChangedEventArgs(property));  
  76.             }  
  77.         }  
  78.         //////////////////////////////////////////////////////////////////////////////  
  79.  
  80.         /// <summary> 
  81.         /// 获取Forecast类  
  82.         /// </summary> 
  83.         public void GetForecast(string cityPinyin)  
  84.         {  
  85.             UriBuilder fullUri = new UriBuilder("http://www.google.com/ig/api");  
  86.             fullUri.Query = "weather=" + cityPinyin;  
  87.             HttpWebRequest forecastRequest = (HttpWebRequest)WebRequest.Create(fullUri.Uri);  
  88.             ForecastUpdateState forecastState = new ForecastUpdateState();  
  89.             forecastState.AsyncRequest = forecastRequest;  
  90.             forecastRequest.BeginGetResponse(new AsyncCallback(HandleForecastResponse),  
  91.                 forecastState);  
  92.         }  
  93.  
  94.         /// <summary> 
  95.         /// 异步获取信息  
  96.         /// </summary> 
  97.         /// <param name="asyncResult"></param> 
  98.         private void HandleForecastResponse(IAsyncResult asyncResult)  
  99.         {  
  100.             ForecastUpdateState forecastState = (ForecastUpdateState)asyncResult.AsyncState;  
  101.             HttpWebRequest forecastRequest = (HttpWebRequest)forecastState.AsyncRequest;  
  102.             forecastState.AsyncResponse = (HttpWebResponse)forecastRequest.EndGetResponse(asyncResult);  
  103.             Stream streamResult;  
  104.             string city = "";  
  105.             string forecast_date = "";  
  106.  
  107.             // 创建一个临时的ForecastPeriod集合  
  108.             ObservableCollection<ForecastPeriod> newnewForecastList =  
  109.                 new ObservableCollection<ForecastPeriod>();  
  110.  
  111.             try  
  112.             {  
  113.                 streamResult = forecastState.AsyncResponse.GetResponseStream();  
  114.                 //加载 XML  
  115.                 XElement xmlWeather = XElement.Load(streamResult);  
  116.  
  117.                 // 解析XML  
  118.                 // http://www.google.com/ig/api?weather=Beijing 
  119.  
  120.                 // 找到forecast_information节点获取city节点和forecast_date节点的信息  
  121.                 XElement xmlCurrent = xmlWeather.Descendants("forecast_information").First();  
  122.                 city = (string)(xmlCurrent.Element("city").Attribute("data"));  
  123.                 forecast_date = (string)(xmlCurrent.Element("forecast_date").Attribute("data"));   
  124.  
  125.                 ForecastPeriod newPeriod;  
  126.                 foreach (XElement curElement in xmlWeather.Descendants("forecast_conditions"))  
  127.                 {  
  128.                     try  
  129.                     {  
  130.                         newnewPeriod = new ForecastPeriod();  
  131.                         newPeriod.Day_of_week = (string)(curElement.Element("day_of_week").Attribute("data"));  
  132.                         newPeriod.Low = (int)(curElement.Element("low").Attribute("data"));  
  133.                         newPeriod.High = (int)(curElement.Element("high").Attribute("data"));  
  134.                         newPeriod.Icon = "http://www.google.com" + (string)(curElement.Element("icon").Attribute("data"));  
  135.                         newPeriod.Condition = (string)(curElement.Element("condition").Attribute("data"));  
  136.                         newForecastList.Add(newPeriod);  
  137.                     }  
  138.                     catch (FormatException)  
  139.                     {  
  140.  
  141.                     }  
  142.                 }  
  143.                 Deployment.Current.Dispatcher.BeginInvoke(() => 
  144.                 {  
  145.                     //赋值City Forecast_date  
  146.                     City = city;  
  147.                     Forecast_date = forecast_date;  
  148.                     ForecastList.Clear();  
  149.  
  150.                     // 赋值ForecastList  
  151.                     foreach (ForecastPeriod forecastPeriod in newForecastList)  
  152.                     {  
  153.                         ForecastList.Add(forecastPeriod);  
  154.                     }  
  155.                 });  
  156.             }  
  157.             catch (FormatException)  
  158.             {  
  159.                 return;  
  160.             }  
  161.  
  162.         }  
  163.     }  
  164.  
  165.     public class ForecastUpdateState  
  166.     {  
  167.         public HttpWebRequest AsyncRequest { get; set; }  
  168.         public HttpWebResponse AsyncResponse { get; set; }  
  169.     }  
  170.  

xml的格式如图

 

 

 



本文转自linzheng 51CTO博客,原文链接:http://blog.51cto.com/linzheng/1078691

相关文章
|
25天前
|
机器学习/深度学习 自然语言处理 数据处理
大模型开发:描述长短期记忆网络(LSTM)和它们在序列数据上的应用。
LSTM,一种RNN变体,设计用于解决RNN处理长期依赖的难题。其核心在于门控机制(输入、遗忘、输出门)和长期记忆单元(细胞状态),能有效捕捉序列数据的长期依赖,广泛应用于语言模型、机器翻译等领域。然而,LSTM也存在计算复杂度高、解释性差和数据依赖性强等问题,需要通过优化和增强策略来改进。
|
29天前
|
数据库 Android开发 开发者
构建高效Android应用:采用Kotlin协程优化网络请求处理
【2月更文挑战第30天】 在移动应用开发领域,网络请求的处理是影响用户体验的关键环节。针对Android平台,利用Kotlin协程能够极大提升异步任务处理的效率和简洁性。本文将探讨如何通过Kotlin协程优化Android应用中的网络请求处理流程,包括协程的基本概念、网络请求的异步执行以及错误处理等方面,旨在帮助开发者构建更加流畅和响应迅速的Android应用。
|
1月前
|
网络协议 Go 开发者
Go语言网络编程基础:构建高效、可靠的网络应用
【2月更文挑战第12天】本文将深入探讨Go语言在网络编程领域的基础知识,包括其强大的并发模型、网络库的使用、TCP/IP和HTTP协议的理解等。通过本文,读者将能够理解Go语言在网络编程中的优势,并掌握构建高效、可靠网络应用的核心技能。
|
1月前
|
数据采集 监控 安全
Go语言在网络安全中的应用
【2月更文挑战第24天】Go语言,作为一种高效且易于维护的编程语言,近年来在网络安全领域得到了广泛的应用。本文旨在探讨Go语言在网络安全中的应用,包括其在防火墙、入侵检测、网络爬虫以及Web安全等方面的应用,并分析了Go语言在网络安全领域的优势与前景。
|
1天前
|
存储 监控 安全
网络安全与信息安全:防范漏洞、应用加密、提升意识
【4月更文挑战第18天】 在数字化时代,网络安全与信息安全保障已成为维护国家安全、企业利益和个人隐私的关键。本文深入探讨网络安全的多面性,包括识别和防御网络漏洞、应用加密技术保护数据以及提升全民网络安全意识的重要性。通过对这些关键领域的分析,文章旨在为读者提供实用的策略和建议,以增强其网络环境的安全防护能力。
4 0
|
2天前
|
数据采集 机器学习/深度学习 数据挖掘
网络数据处理中的NumPy应用实战
【4月更文挑战第17天】本文介绍了NumPy在网络数据处理中的应用,包括数据预处理、流量分析和模式识别。通过使用NumPy进行数据清洗、格式化和聚合,以及处理时间序列数据和计算统计指标,可以有效进行流量分析和异常检测。此外,NumPy还支持相关性分析、周期性检测和聚类分析,助力模式识别。作为强大的科学计算库,NumPy在处理日益增长的网络数据中发挥着不可或缺的作用。
|
10天前
|
传感器 监控 安全
|
10天前
|
安全 SDN 数据中心
|
10天前
|
安全 网络安全 网络虚拟化
虚拟网络设备与网络安全:深入分析与实践应用
在数字化时代📲,网络安全🔒成为了企业和个人防御体系中不可或缺的一部分。随着网络攻击的日益复杂和频繁🔥,传统的物理网络安全措施已经无法满足快速发展的需求。虚拟网络设备🖧,作为网络架构中的重要组成部分,通过提供灵活的配置和强大的隔离能力🛡️,为网络安全提供了新的保障。本文将从多个维度深入分析虚拟网络设备是如何保障网络安全的,以及它们的实际意义和应用场景。
|
25天前
|
机器学习/深度学习 PyTorch 算法框架/工具
卷积神经元网络中常用卷积核理解及基于Pytorch的实例应用(附完整代码)
卷积神经元网络中常用卷积核理解及基于Pytorch的实例应用(附完整代码)
20 0

热门文章

最新文章