659441806 发表于 2015-5-13 13:45:57

windows phone 7 31-4:设备方向

  原文地址:http://www.jeffblankenburg.com/post/31-Days-of-Windows-Phone-7c-Day-4-Device-Orientation.aspx
  这是31天学习windows phone 的第四天。
  昨天,我们已经讨论了windows phone上的一个专用按钮---返回按钮。今天,我们将会把注意力放在英俊爱你的另一个方面:设备方向
Portrait vs. Landscape
  尽管不太明显,portrait是设备的垂直放置方向,而landscape是水平放置方向。这些在任意的wp7程序上都是可以设置的,但是默认情况下,Silverlight程序开始于portrait,而XNA开始于landscape。(游戏一般都是需要更大的屏幕)。在这篇文章中,我们将会将注意力放在Silverlight上,以及我们如何处理用户在使用程序时将设配方向改变的情况。
  你的默认工程将会是“portrai-only”
  如果你看一下MainPage.xaml文件的头信息,你将会看到两个属性:
SupportedOrientations="Portrait" Orientation="Portrait"
  将SupportedOrientations看成你的程序支持列表。你可以将它设置成以下属性值之一:


[*]Portrait (the default)
[*]Landscape
[*]PortraitOrLandscape
  Orientation值是你希望程序开始使用时的设定。他有很多值,但是记住如果要从landscape开始,你必须将landscape设置为选项。如下是orientation的起始值:


[*]Landscape
[*]LandscapeLeft (tip the phone left)
[*]LandscapeRight (tip the phone right)
[*]Portrait
[*]PortraitDown (normal vertical position)
[*]PortraitUp (tip the phone upside-down)
  从上边你可以知道不仅可以设置使用landscape或是portrait启动,你还可以设置这些方向的定位。这将会允许你从你所喜欢的方向定位开始你的程序。

改变方向
  有两种方式将布局改变。第一种是将SupportedOrientation设置为“PortraitOrLandscape”然后让系统帮助你来进行设置。许多情况下,这不被推荐,因为你的程序将有很大可能不能够自适应屏幕。第二种方式是通过具体的代码实现,这也正是我们将会说到的。
  让我们使用一个垂直启动方向的程序进行示范。如下是例子:

  你看到在landscape情况下,许多按钮都开始偏离屏幕。这是一个不好的用户体验。一种比较方便的方式是丢弃title,我确信我们的程序用户将会知道这是一个计算器,所以也许当他们在landscape模式下时,我们可以讲title去掉。我们可以同样重新排布我们的按钮,如果这些对你的程序有更大的帮助就做吧。本文的目的是展示如何修改程序,而不是指示你具体要修改什么。这是我使title小时并且修复问题的代码:



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(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;
}
}
}
}
  因为我只是关注于程序是landscape还是portrait,我正在只是检测这两种状态。你当然可以自己根据需要设置不同的代码。
  你注意到我为这个OrientationChanged创建了一个事件处理。这是识别发生时间的最简单方式,但是你还可以通过Accelerometer,这些将会在第十一天讲到。下面是代码运行以后的画面:
页: [1]
查看完整版本: windows phone 7 31-4:设备方向