0

我试图在 OnMeasure 方法中返回相同的大小。如果我将自定义控件的 RowDefinition 值设置为 auto,则自定义控件也会在下一行定义空间中呈现。

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

示例:CustomControl 示例

[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)控件时,意味着工作正常。请对此提出任何建议。

4

1 回答 1

1

BoxView 类中,BoxView 的默认大小请求为 40x40。所以你不需要重写 SizeRequest OnMeasure。

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

 public class MyBoxView : BoxView
{
    public MyBoxView()
    {

    }
   
}

更新:

OnMeasure 方法可能会被调用,这取决于 MyBoxView 的放置位置以及任何外部布局的约束。例如,如果 MyBoxView 在 Grid.Row 内,并且行高为“*”,则不会调用 OnMeasure。当外部布局询问“您需要多少空间?”时调用 OnMeasure。在“*”的情况下,我们可以把它想象成“这是你有多少空间”。

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

这个 MyBoxView 将利用所有可用的宽度或高度来创建一个正方形的布局空间。因此,在这种布局在具有“自动”大小的 GridLayout 中的情况下,MyBoxView 只会说它需要基于两者中的最小值的相等的宽度和高度。

所以最好的方法是设置 RowDefinitions height=value 或者直接设置 MyBoxView 的高度。

于 2021-04-12T12:26:19.220 回答