技术开发 频道

从Web到Windows phone的快速开发

  【IT168技术】由于Windows Phone 7的开发技术之一是Silverlight,自然我们会想到,能否将silverlight开发的web程序快速迁移到wp7中,要想实现快速迁移,唯一的办法是重用。目前大部分网站的开发都是三层架构,显然UI层面肯定是无法重用的,因为桌面程序和移动应用的UI设计非常不同,能重用的就是业务逻辑层和Model层,这篇文章以一个简单的在线相片浏览器程序为例,演示如何将业务逻辑层进行封装供Web与WP7使用,以及需要注意的问题。

  一个在线照片浏览器的开发主要包括三个部分,第一部分是服务器端提供数据模块,该模块将照片的信息(比如Uri,照片说明等)以json或xml的格式返回给客户端,这部分对于web应用和wp7应用都是一样的,不需要改动。第二个部分是在客户端的数据获取模块,主要是构建数据请求,异步接收数据,解析数据成客户端需要的数据模型,这部分是我们封装的重点。第三部分是将获取的数据与照片浏览控件进行绑定,这部分需要在wp7上开发。

  首先我们定义简单的数据模型,主要就是照片的Uri和说明文字,另外还有一个缩略图的Uri:

  以下是代码片段:

  public class PhotoItem

  {

  public Uri ImageUri

  {

  set { imageUri = value; }

  }

  public Uri ThumbImageUri { get; set; }

  ///

  /// Gets BitmapImage from imageUri.

  ///

  public BitmapImage ImageSource

  {

  get { return new BitmapImage(imageUri); }

  }

  public string Description

  {

  get { return description; }

  set { description = value; }

  }

  }

  首先定义一个事件参数,用来传递请求下来的数据给客户端页面程序:

  以下是代码片段:

  public class RequestEventArgs : EventArgs

  {

  private bool _loadCompleted;

  private object _result;

  public object Result { get { return _result; } }

  public bool LoadCompleted { get { return _loadCompleted; } }

  public RequestEventArgs(bool loadCompleted, object result)

  {

  this._loadCompleted = loadCompleted;

  this._result = result;

  }

  }

  然后用一个PhotoAlbum类来封装数据的获取:

  以下是代码片段:

  public class PhotoAlbum

  {

  private List _photoes;

  private Uri _serverUri;

  public event EventHandler PhotoAlbumLoaded;

  public void LoadSchedulePhotoes(Uri baseUri)

  {

  _serverUri = baseUri;

  //将Http请求封装在一个帮助类中,网上有很多这样的封装类

  HttpHelper httpRequest = new HttpHelper();

  httpRequest.CommunicationCompleted += ResponseHandler;

  httpRequest.CommunicationFailed += RequestFailedHandle;

  httpRequest.ExecuteGet(baseUri.AbsolutePath + "/Controller/action", false); //这里指定Controller和action

  }

  public void ResponseHandler(string json)

  {

  //将Json转换成我们需要的数据类型

  List _photoes = JsonConvert.DeserializeObject>(json);

  //拿到数据后激发事件

  PhotoAlbumLoaded(this, new RequestEventArgs(true, _photoes));

  }

  public void RequestFailedHandle(string json)

  {

  //做错误处理

  }

  }

  有了上面的东西,在web和wp7程序上,我们只需要简单的创建一个PhotoAlbum,然后绑定PhotoAlbumLoaded事件,在事件中将参数中的Result绑定到照片浏览控件上,然后调用LoadSchedulePhotoes(Uri baseUri)函数即可。

  需要注意的是为什么将baseUri作为参数而不直接封装在类里面,我们知道在Web的silverlight程序,我们可以通过Browser获取服务器的Uri,但是在WP7的应用程序,我们没办法这样获得服务器地址,如果在开发web程序中将服务器Uri封装在业务逻辑类中,在WP7上就没办法直接用了。

  通过这个简单的例子,主要想说明的是,在用Silverlight开发RIA应用的时候,我们应该尽量将业务逻辑和数据模型封装成单独的dll,并且要充分考虑平台的不同,这样能达到重用的目的,实现快速的应用迁移。

0
相关文章