CustomControl 计算自己的宽度和高度 - ArrangeOverride 被调用 bounds.Height=0

CustomControl calculate own width and height - ArrangeOverride gets called with bounds.Height=0

我正在尝试将“扑克牌”实现为 ContentView,它按比例计算其宽度和高度。 ContentView 的内容是带有一些标签的网格。在计算扑克牌控件的Size时,我需要告诉child/grid它能占据多大的尺寸。在我第一次尝试使用 MeasureOverrideArrangeOverride 时,看起来我的所有尝试在设置大小时都被忽略了。我简化了整个代码以仅设置控件的最小尺寸,但尺寸仍然被忽略。

值得注意 ArrangeOverride(Rect bounds) 使用以下参数值 bounds = { X=0, Y=0, Width=1013, Height=0 } 调用。为什么高度为0?我什至将 OnMeasure 中的最小高度声明为 85,并且还有更多 space 可用。我在这里做错了什么?

后面的自定义控件代码:

    public partial class CardView : ContentView
    {
        private const double minWidth = 55;
        private const double minHeight = 85;
        public CardView()
        {
            InitializeComponent();
            BackgroundColor = Colors.BlueViolet;
        }
        protected override Size MeasureOverride(double widthConstraint, double heightConstraint)
        {
            //define minimum size of control
            var minSize = new Size(minWidth, minHeight);
            System.Diagnostics.Debug.WriteLine($"MeasureOverride width={minSize.Width},height={minSize.Height}");
            return minSize;
        }
        protected override Size ArrangeOverride(Rect bounds) //bounds = { X=0, Y=0, Width=1013, Height=0 } 
        {
            Rect rect = new Rect(0, 0, minWidth, minHeight);
            grid.WidthRequest = minWidth;
            grid.HeightRequest = minHeight;
            //grid.Arrange(rect); //results int Layout cycle detected.  Layout could not complete.
            System.Diagnostics.Debug.WriteLine($"ArrangeOverride width={minWidth},height={minWidth}");
            return new Size(minWidth, minHeight);
        }
        protected override void OnSizeAllocated(double width, double height)
        {
            base.OnSizeAllocated(width, height);
            System.Diagnostics.Debug.WriteLine($"OnSizeAllocated width={width},height={height}");
        }
    }

xaml代码

<?xml version="1.0" encoding="UTF-8"?>
<ContentView xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="CustomLayouts.CardView"
             BackgroundColor="Red">
  <ContentView.Content>
        <Grid x:Name="grid" BackgroundColor="DarkRed">
            <Label Text="1" />
        </Grid>
  </ContentView.Content>
</ContentView>

[编辑]输出如下:

OnSizeAllocated width=-1,height=-1
MeasureOverride width=55,height=85
MeasureOverride width=55,height=85
OnSizeAllocated width=1013,height=0
ArrangeOverride width=55,height=55
MeasureOverride width=55,height=85

网格和卡片控件的大小为=1013,高度=0。

我在这里创建了一个示例存储库:https://github.com/mfe-/CustomLayoutExamples。非常感谢任何帮助。

自定义控件的测量和布局有一个未解决的问题,这似乎会导致您遇到的问题:https://github.com/dotnet/maui/issues/4019