在旋转 phone 时更改 CollectionView 的跨度不起作用

Changing the span of CollectionView while rotating phone isn't working

我试图在旋转 iPhone 时更改 CollectionView 的跨度。为方便起见,只需纵向显示 2 列,横向显示 4 列。 它在从纵向模式旋转到横向模式时有效,但当旋转回纵向模式时,它始终显示 1 列。我的代码喜欢,

    VideoCollectionView = new CollectionView()
        {
            ItemsLayout = new GridItemsLayout(2, ItemsLayoutOrientation.Vertical),
        };
    ...

    private static double screen_width = 1280.0;
    private static double screen_height = 720.0;

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

        if ((Math.Abs(screen_width - width) > minimum_double) || (Math.Abs(screen_height - height) > minimum_double))
        {
            screen_width = width;
            screen_height = height;

            int split;
            if (screen_width > screen_height)
            {   // landscape mode
                split = 4;
            }
            else
            {   // portrait mode
                split = 2;
            }

            VideoCollectionView.ItemsLayout = new GridItemsLayout(split, ItemsLayoutOrientation.Vertical);
        }
    }

这是一个错误吗?或者我应该使用其他方式?感谢您的帮助。

您可以使用 Singleton 来存储当前 orientation.Because 将屏幕大小设置为 s 静态值是不明智的。它可能会导致不同尺寸的设备出现问题。

public class CurrentDevice
{
    protected static CurrentDevice Instance;
    double width;
    double height;

    static CurrentDevice()
    {
        Instance = new CurrentDevice();
    }
    protected CurrentDevice()
    {
    }

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

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

并且在方法中

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


   if (CurrentDevice.IsOrientationPortrait() && width > height || !CurrentDevice.IsOrientationPortrait() && width < height)
   {
      int split;
      CurrentDevice.SetSize(width, height);

      // Orientation got changed! Do your changes here
      if (CurrentDevice.IsOrientationPortrait())
      {
         // portrait mode
         split = 2;
      }

      else
      {
         // landscape mode
         split = 4;
      }

      VideoCollectionView.ItemsLayout = new GridItemsLayout(split, ItemsLayoutOrientation.Vertical);
   }


}