Windows Phone 开发之 设备方向

默认项目是“只支持纵向的”

如果你看一下MainPage.xaml文件的头部信息,会发现两个属性:SupportedOrientations=”Portrait” Orientation=”Portrait”

可以将SupportedOrientations想象成你准备在程序中支持的可能发生的情况的列表。你可以将SupportedOrientations设置成以下3个值中的任意一个:

  • Portrait (默认值)
  • Landscape
  • PortraitOrLandscape

Orientation属性是想让你的程序在启动时以何种方式呈现。它有更多的值可选,但记住如果想要以 模式启动,你需要将横向包含到SupportedOrientations中。下面是Orientation值的列表:

  • Landscape
  • LandscapeLeft (将电话向左翻转)
  • LandscapeRight (将电话向右翻转)
  • Portrait
  • PortraitDown (正常的竖直方向)
  • PortraitUp (倒置)

你可以看到在上表中不仅可以指定纵向或横向,还可以指定这些方向的排列方式。这允许你用你喜欢的方向开始你的应用程序。

改变方向

有两种方式可以改变设备的方向。第一将SupportedOrientation设置为“PortraitOrLandscape”让操作系统为你实现。在大多数情况下,并不推荐这样做,因为你的应用程序界面可能不再适应屏幕了。第二种方式是通过代码实现。

你可以看到在横向时,很多按钮不在屏幕之中。这不是理想的用户体验。简单解决方法是去掉标题。我确信我们的用户可以看出这是一个计算器。我们可以对按钮进行重新布局,如果对于程序来说有意义,那就去做!本篇文章的目的是告诉你如何 改变你的程序,而不是告诉你应该改变什么 。我用了以下的代码来使标题栏消失和重现(这是MainPage.xaml.cs文件的全部内容):

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
namespace Day4_DeviceOrientation
{
public partial class MainPage : PhoneApplicationPage
{
// Constructor
public MainPage()
{
InitializeComponent();
this.OrientationChanged += new EventHandler<OrientationChangedEventArgs>(MainPage_OrientationChanged);
}
void MainPage_OrientationChanged(object sender, OrientationChangedEventArgs e)
{
if ((e.Orientation == PageOrientation.LandscapeRight)||(e.Orientation == PageOrientation.LandscapeLeft))
{
TitlePanel.Visibility = Visibility.Collapsed;
}
else if ((e.Orientation == PageOrientation.PortraitDown) || (e.Orientation == PageOrientation.PortraitUp))
{
TitlePanel.Visibility = Visibility.Visible;
}
}
}
}

因为我只关注程序是横向还是纵向(而不是所有的方向),所以同时检测这两个状态并相应地调整界面。你可以将每种情况分开处理使界面看起来不同。

注意我为OrientationChanged事件创建的处理程序。这是一个在方向改变时最简单的识别方法,通常你可以使用将在第11天介绍的加速计。


posted @ 2011-10-12 21:55  javawebsoa  Views(184)  Comments(0Edit  收藏  举报