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

 

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

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

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的格式如图

 

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