11

如何检测 Xamarin Forms 中的屏幕方向变化?我需要改变对方向变化的看法,我应该怎么做才能触发方向变化的变化?提供链接或示例代码将非常有帮助。

提前致谢

4

2 回答 2

12

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

 static bool IsPortrait(Page p) { return p.Width < p.Height; }
于 2015-01-06T18:56:51.423 回答
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
        }
}

单例类

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;
    }
}
于 2014-07-10T07:40:57.623 回答