设为首页 收藏本站
查看: 1177|回复: 0

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

[复制链接]
累计签到:2 天
连续签到:1 天
发表于 2015-5-8 09:35:49 | 显示全部楼层 |阅读模式
  天气预报应用是通过异步调用Google天气api(http://www.google.com/ig/api?weather=城市拼音),对其进行xml的数据解析,将其数据简单的展现出在Windows Phone 7的客户端上。
DSC0000.jpg DSC0001.jpg
  首页的城市数据绑定类,以及预设好的城市列表
  City.cs


DSC0002.gif DSC0003.gif View Code



using System.ComponentModel;
namespace WeatherForecast
{
    ///
    /// 城市绑定类
    ///
    public class City : INotifyPropertyChanged
    {
        private string cityPinyin;//城市拼音
        private string province;//省份
        private string cityName;//城市名称

        public string CityPinyin
        {
            get
            {
                return cityPinyin;
            }
            set
            {
                if (value != cityPinyin)
                {
                    cityPinyin = value;
                    NotifyPropertyChanged("CityPinyin");
                }
            }
        }
        public string Province
        {
            get
            {
                return province;
            }
            set
            {
                if (value != province)
                {
                    province = value;
                    NotifyPropertyChanged("Province");
                }
            }
        }
        public string CityName
        {
            get
            {
                return cityName;
            }
            set
            {
                if (value != cityName)
                {
                    cityName = value;
                    NotifyPropertyChanged("CityName");
                }
            }
        }
        public event PropertyChangedEventHandler PropertyChanged;
        ///
        /// 构造city类
        ///
        public City(string cityPinyin, string province, string cityName)
        {
            CityPinyin = cityPinyin;
            Province = province;
            CityName = cityName;
        }
        ///
        ///用于绑定属性值改变触发的事件,动态改变
        ///
        private void NotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
    }
}
  Cities.cs


View Code



using System.Collections.ObjectModel;
namespace WeatherForecast
{
    ///
    /// 继承 ObservableCollection用户数据绑定
    ///
    public class Cities : ObservableCollection
    {
        public Cities() { }
        ///
        /// 设置默认的绑定城市 利用App类里面定义的静态变量cityList
        ///
        public void LoadDefaultData()
        {
            App.cityList.Add(new City("Shenzhen", "广东省", "深圳市"));
            App.cityList.Add(new City("Beijing", "北京市", "北京市"));
            App.cityList.Add(new City("Shanghai", "上海市", "上海市"));
            App.cityList.Add(new City("Guangzhou", "广东省", "广州市"));
            App.cityList.Add(new City("Yangjiang", "广东省", "阳江市"));
        }
    }
}
  对首页城市列表的绑定需要在app程序启动类里面赋值
  App.xaml.cs需要添加获取城市列表的代码
  public static Cities cityList;//绑定的城市列表
  ……
  private void Application_Launching(object sender, LaunchingEventArgs e)
        {
            // 创建城市列表
            if ( cityList==null)
            {
                cityList = new Cities();
                cityList.LoadDefaultData();
            }
        }
  首页的界面设计代码





   
        
            
            
        
        
            
        
        
            
               
                    
                        
                           
                           
                                
                                
                                
                                
                           
                        
                    
               
            
        
   




using System;
using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
namespace WeatherForecast
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();
            CityList.ItemsSource = App.cityList;//绑定城市列表
        }
        ///
        /// 获取天气预报事件
        ///
        private void CityList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            // 如果列被选中
            if (CityList.SelectedIndex != -1)
            {
                City curCity = (City)CityList.SelectedItem;//获取当前选中的城市的绑定的类
                this.NavigationService.Navigate(new Uri("/ForecastPage.xaml?City=" +
                    curCity.CityPinyin, UriKind.Relative));//跳转向ForecastPage.xaml  并传递参数CityPinyin  接口要用到城市的拼音
            }
        }
        ///
        /// 跳转到ForecastPage.xaml页面前执行该事件
        ///
        protected override void OnNavigatedFrom(NavigationEventArgs args)
        {
            // 清空选中的列
            CityList.SelectedIndex = -1;
            CityList.SelectedItem = null;
        }
    }
}
  第二个界面  异步调用Google的天气api,解析xml,然后绑定到客户端
  天气预报类
  ForecastPeriod.cs


View Code



using System.ComponentModel;
namespace WeatherForecast
{
    ///
    /// 天气预报绑定类
    ///
    public class ForecastPeriod : INotifyPropertyChanged
    {
        private string day_of_week;//星期
        private int low;//最低温度
        private int high;//最高温度
        private string icon;//图片地址
        private string condition;//天气情况

        public event PropertyChangedEventHandler PropertyChanged;
        public ForecastPeriod()
        {
        }
        public string Day_of_week
        {
            get
            {
                return day_of_week;
            }
            set
            {
                if (value != day_of_week)
                {
                    this.day_of_week = value;
                    NotifyPropertyChanged("Day_of_week");
                }
            }
        }
        public int Low
        {
            get
            {
                return low;
            }
            set
            {
                if (value != low)
                {
                    this.low = value;
                    NotifyPropertyChanged("Low");
                }
            }
        }
        public int High
        {
            get
            {
                return high;
            }
            set
            {
                if (value != high)
                {
                    this.high = value;
                    NotifyPropertyChanged("High");
                }
            }
        }
        public string Icon
        {
            get
            {
                return icon;
            }
            set
            {
                if (value != icon)
                {
                    this.icon = value;
                    NotifyPropertyChanged("Icon");
                }
            }
        }
        public string Condition
        {
            get
            {
                return condition;
            }
            set
            {
                if (value != condition)
                {
                    this.condition = value;
                    NotifyPropertyChanged("Condition");
                }
            }
        }
        private void NotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
    }
}
  天气预报列表类 以及异步调用解析的方法
  Forecast.cs


View Code



using System;
using System.Net;
using System.Windows;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Xml.Linq;

namespace WeatherForecast
{
    ///
    /// 天气类以及处理解析异步请求
    ///
    public class Forecast : INotifyPropertyChanged
    {
        // 天气预报的城市
        private string city;
        // 天气预报的时间
        private string forecast_date;
        public event PropertyChangedEventHandler PropertyChanged;
        // 不同时间段的天气预报集合
        public ObservableCollection ForecastList
        {
            get;
            set;
        }
        public String City
        {
            get
            {
                return city;
            }
            set
            {
                if (value != city)
                {
                    city = value;
                    NotifyPropertyChanged("City");
                }
            }
        }
        public String Forecast_date
        {
            get
            {
                return forecast_date;
            }
            set
            {
                if (value != forecast_date)
                {
                    forecast_date = value;
                    NotifyPropertyChanged("Forecast_date");
                }
            }
        }
        public Forecast()
        {
            ForecastList = new ObservableCollection();
        }
        private void NotifyPropertyChanged(string property)
        {
            if (PropertyChanged != null)
            {
                PropertyChanged(this, new PropertyChangedEventArgs(property));
            }
        }
        //////////////////////////////////////////////////////////////////////////////
        ///
        /// 获取Forecast类
        ///
        public void GetForecast(string cityPinyin)
        {
            UriBuilder fullUri = new UriBuilder("http://www.google.com/ig/api");
            fullUri.Query = "weather=" + cityPinyin;
            HttpWebRequest forecastRequest = (HttpWebRequest)WebRequest.Create(fullUri.Uri);
            ForecastUpdateState forecastState = new ForecastUpdateState();
            forecastState.AsyncRequest = forecastRequest;
            forecastRequest.BeginGetResponse(new AsyncCallback(HandleForecastResponse),
                forecastState);
        }
        ///
        /// 异步获取信息
        ///
        ///
        private void HandleForecastResponse(IAsyncResult asyncResult)
        {
            ForecastUpdateState forecastState = (ForecastUpdateState)asyncResult.AsyncState;
            HttpWebRequest forecastRequest = (HttpWebRequest)forecastState.AsyncRequest;
            forecastState.AsyncResponse = (HttpWebResponse)forecastRequest.EndGetResponse(asyncResult);
            Stream streamResult;
            string city = "";
            string forecast_date = "";
            // 创建一个临时的ForecastPeriod集合
            ObservableCollection newForecastList =
                new ObservableCollection();
            try
            {
                streamResult = forecastState.AsyncResponse.GetResponseStream();
                //加载 XML
                XElement xmlWeather = XElement.Load(streamResult);
                // 解析XML
                // http://www.google.com/ig/api?weather=Beijing
                // 找到forecast_information节点获取city节点和forecast_date节点的信息
                XElement xmlCurrent = xmlWeather.Descendants("forecast_information").First();
                city = (string)(xmlCurrent.Element("city").Attribute("data"));
                forecast_date = (string)(xmlCurrent.Element("forecast_date").Attribute("data"));
                ForecastPeriod newPeriod;
                foreach (XElement curElement in xmlWeather.Descendants("forecast_conditions"))
                {
                    try
                    {
                        newPeriod = new ForecastPeriod();
                        newPeriod.Day_of_week = (string)(curElement.Element("day_of_week").Attribute("data"));
                        newPeriod.Low = (int)(curElement.Element("low").Attribute("data"));
                        newPeriod.High = (int)(curElement.Element("high").Attribute("data"));
                        newPeriod.Icon = "http://www.google.com" + (string)(curElement.Element("icon").Attribute("data"));
                        newPeriod.Condition = (string)(curElement.Element("condition").Attribute("data"));
                        newForecastList.Add(newPeriod);
                    }
                    catch (FormatException)
                    {
                    }
                }
                Deployment.Current.Dispatcher.BeginInvoke(() =>
                {
                    //赋值City Forecast_date
                    City = city;
                    Forecast_date = forecast_date;
                    ForecastList.Clear();
                    // 赋值ForecastList
                    foreach (ForecastPeriod forecastPeriod in newForecastList)
                    {
                        ForecastList.Add(forecastPeriod);
                    }
                });
            }
            catch (FormatException)
            {
                return;
            }
        }
    }
    public class ForecastUpdateState
    {
        public HttpWebRequest AsyncRequest { get; set; }
        public HttpWebResponse AsyncResponse { get; set; }
    }
}
  xml的格式如图
DSC0004.jpg
  第二个页面的代码
  ForecastPage.xaml





   
        
            
            
        
        
            
            
        
        
            
               
                    
                        
                           
                                
                                
                                
                                
                           
                           
                                
                                
                                
                                
                           
                           
                           
                           
                           
                           
                           
                           
                        
                    
               
            
        
   




using System.Windows.Controls;
using Microsoft.Phone.Controls;
using System.Windows.Navigation;
namespace WeatherForecast
{
    public partial class ForecastPage : PhoneApplicationPage
    {
        Forecast forecast;
        public ForecastPage()
        {
            InitializeComponent();
        }
        ///
        /// 当该页面被链接打开时,会调用该事件
        ///
        protected override void OnNavigatedTo(NavigationEventArgs e)
        {
            // 获取传过来的City值
            string cityPinyin = this.NavigationContext.QueryString["City"];
            forecast = new Forecast();
            //获取天气类
            forecast.GetForecast(cityPinyin);
            // 设置页面数据绑定到forecast
            DataContext = forecast;
            // 设置ForecastList绑定到forecast.ForecastList
            ForecastList.ItemsSource = forecast.ForecastList;
        }
        private void ForecastList_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            ForecastList.SelectedIndex = -1;
            ForecastList.SelectedItem = null;
        }
    }
}

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-64880-1-1.html 上篇帖子: 编程累了,一起来看电视吧,实战Windows 7的Windows Media Center。 下篇帖子: 《深入浅出:Windows Phone 7应用开发》
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表