在行定义中将高度设置为自动时,自定义控件占满 space

Custom control takes full space while setting Height as Auto in row definition

我试图在 OnMeasure 方法中 return 相同的尺寸。如果我将自定义控件的 RowDefinition 值设置为 auto,自定义控件也会在下一个行定义中呈现 space。

自定义控件呈现在第 3 行和第 4 行中,第 4 行控件在屏幕上不可见。

样本:CustomControl sample

[Xaml]

<Grid ColumnDefinitions="*,0.3*" RowDefinitions="auto,200,auto,auto">
          <Button BackgroundColor="Blue" Grid.Row="0" Grid.Column="0" Grid.ColumnSpan="2" ></Button>
          <Button BackgroundColor="Green" Grid.Row="1" Grid.Column="0" Grid.ColumnSpan="2" ></Button>
      
          <local:MyBoxView  BackgroundColor="Red" Grid.Row="2" Grid.Column="0" Grid.ColumnSpan="2" />
           
          <Button Text="Button" BackgroundColor="Brown" Grid.Row="3" Grid.Column="0" Grid.ColumnSpan="2" />


     </Grid>

[C#]

public class MyBoxView : BoxView
{
    public MyBoxView()
    {



    }
    protected override SizeRequest OnMeasure(double widthConstraint, double heightConstraint)
    {
        return new SizeRequest(new Size(widthConstraint, heightConstraint));
    }
}

当我在网格视图中添加自定义 (MyBoxview) 控件时,表示工作正常。请对此提出任何建议。

来自 BoxView Class,BoxView 的默认尺寸请求为 40x40。所以你不需要重写 SizeRequest OnMeasure。

请移除 SizeRequest OnMeasure 方法,然后您将获得相同大小的 boxview。

 public class MyBoxView : BoxView
{
    public MyBoxView()
    {

    }
   
}

更新:

可以调用 OnMeasure 方法,这取决于我们的 MyBoxView 的放置位置以及任何外部布局的约束。例如,如果 MyBoxView 在 Grid.Row 内且行高为“*”,则不会调用 OnMeasure。当外部布局询问“你需要多少space?”时调用 OnMeasure。在“*”的情况下,我们可以将其更像是“这就是你有多少space”。

在调用 OnMeasure 的情况下,widthConstraint 或 heightConstaint 可能会设置为无穷大。例如,如果 MyBoxView 在 StackLayout 中,纵向的 StackLayout 将不会限制高度,因此 heightConstraint 将被设置为无穷大。同样,对于横向,widthConstraint 将设置为无穷大。因此,当您从 OnMeasure 计算 return 的 SizeRequest 时,您将需要处理无穷大的情况。

这个 MyBoxView 将采用所有可用的宽度或高度来创建正方形布局 space。因此,如果此布局位于具有“自动”调整大小的 GridLayout 中,MyBoxView 只会说它需要基于两者中的最小值的相等宽度和高度。

所以最好的办法是设置RowDefinitions height=value 或者直接设置MyBoxView height