You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

MAUI自定义控件重写ArrangeOverride后按钮点击事件失效求助

问题原因

重写ArrangeOverride时返回了空的Size实例(宽高均为0),导致自定义控件Page1的实际布局区域被系统判定为无尺寸空间。虽然按钮能被渲染出来,但MAUI的点击事件命中检测是基于控件的布局边界的,点击位置不在Page1的有效区域内,所以事件无法传递到内部的Button。另外MeasureOverride返回空尺寸也会干扰布局系统的正常计算。

解决方案

需要在两个重写方法中返回正确的控件尺寸:

1. 修正MeasureOverride方法

计算所有子元素的总尺寸,返回能容纳所有按钮的最小尺寸:

protected override Microsoft.Maui.Graphics.Size MeasureOverride(double widthConstraint, double heightConstraint)
{
    double totalWidth = 0;
    double totalHeight = 10; // 初始Y偏移量
    int index = 0;
    foreach (var c in this.Children)
    {
        var childSize = c.Measure(widthConstraint, heightConstraint);
        wdt[index] = (byte)childSize.Width;
        totalWidth = Math.Max(totalWidth, childSize.Width + 50); // 每个按钮的宽度+间距
        totalHeight += childSize.Height + 40; // 每个按钮的高度+Y方向间距
        index++;
    }
    return new Microsoft.Maui.Graphics.Size(totalWidth, totalHeight);
}

2. 修正ArrangeOverride方法

计算所有按钮排列后的总宽高,赋值给finalSize并返回:

protected override Microsoft.Maui.Graphics.Size ArrangeOverride(Rect bounds)
{
    var lct = new Microsoft.Maui.Graphics.Point();
    double totalWidth = 0;
    double totalHeight = 10;
    int x = 0, y = 10;
    for (int i = 0; i < n; i++)
    {
        lct.X = x;
        lct.Y = y;
        var c = Children[i];
        var childSize = c.DesiredSize;
        c.Arrange(new Rect(lct, childSize));
        // 更新总尺寸
        totalWidth = Math.Max(totalWidth, x + childSize.Width);
        totalHeight = y + childSize.Height;
        x += wdt[i] + 50;
        y += 40;
    }
    // 返回控件实际占用的尺寸
    return new Microsoft.Maui.Graphics.Size(totalWidth, totalHeight);
}

额外优化点

  • 避免使用固定长度的byte[] wdt,可以改用List<double>来存储子元素宽度,避免数组越界风险:
    List<double> wdt = new List<double>();
    // 在Add方法中添加:
    wdt.Add(0); // 后续在MeasureOverride中更新
    

这样修改后,自定义控件会正确报告自己的布局尺寸,点击事件就能正常命中内部的按钮了。

内容的提问来源于stack exchange,提问作者JuSul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 17:53:27