如何在Xamarin.Forms中检测设备的屏幕方向?

时间:2014-07-09 14:42:06

标签: xamarin cross-platform xamarin.forms

如何检测Xamarin Forms中的屏幕方向变化?我需要更改方向更改的视图,我应该怎么做以触发方向更改的更改?提供链接或示例代码将非常有用。

提前致谢

2 个答案:

答案 0 :(得分:12)

我尝试了依赖注入,但还没有成功。现在,我解决了这个问题:

  • 使用OnSizeAllocated(double, double)更改方向更改时的屏幕。
  • 使用Singleton存储当前方向。

Xamarin.Forms页面  

protected override void OnSizeAllocated(double width, double height)
{
    base.OnSizeAllocated(width, height);

    if (DeviceInfo.IsOrientationPortrait() && width > height || !DeviceInfo.IsOrientationPortrait() && width < height)
        {
            // Orientation got changed! Do your changes here
        }
}

Singleton Class  

public class DeviceInfo
{
    protected static DeviceInfo _instance;
    double width;
    double height;

    static DeviceInfo()
    {
        _instance = new DeviceInfo();
    }
    protected DeviceInfo()
    {
    }

    public static bool IsOrientationPortrait() 
    {
        return _instance.height > _instance.width;
    }

    public static void SetSize(double width, double height)
    {
        _instance.width = width;
        _instance.height = height;
    }
}

答案 1 :(得分:9)

只需将其添加到您的页面,或者更好的是您的BasePage:

 static bool IsPortrait(Page p) { return p.Width < p.Height; }