MAUI: button not working in custom element (in derived class)

I'm trying to create a custom control in Maui from several buttons.  
public class Page1 : StackLayout
{  
    int i, n=0;
    byte[] wdt = new byte[255];  
    public void Add(string t)  
    {  
      Button bt = new Button      {  
        Text = t, 
        BorderWidth = 1,
        BorderColor = Colors.Black,
        BackgroundColor = Colors.Transparent,
        TextColor = Colors.Black,
        Padding = new Thickness(2, 0),
        HeightRequest = 30,
        IsEnabled = true,        
      };  
      bt.Clicked += OnButtonClicked;  
      Children.Add(bt);  
      n++;  
    }
    protected override Microsoft.Maui.Graphics.Size MeasureOverride(double widthConstraint, double heightConstraint)
    {
      var size = base.MeasureOverride(widthConstraint, heightConstraint);
      var mySize = new Microsoft.Maui.Graphics.Size();
      i = 0;
      foreach (var c in this.Children)
      {
        wdt[i] = (byte)(c.DesiredSize.Width);
        i++;
      }
      return mySize;
    }
    protected override Microsoft.Maui.Graphics.Size ArrangeOverride(Rect bounds)
    {
      var lct = new Microsoft.Maui.Graphics.Point();
      Microsoft.Maui.Graphics.Size finalSize = new();
      int x = 0, y = 10;
      for (i = 0; i < n; i++)
      {
        lct.X = x;
        lct.Y = y;
        var c = Children[i];
        c.Arrange(new Rect(lct, c.DesiredSize));
        x += wdt[i] + 50;
        y += 40;
      }
      return finalSize;
    }  
    private void OnButtonClicked(object sender, System.EventArgs e)  
    {
      Button bt = (Button)sender;  
      if(bt.BackgroundColor== Colors.LightPink)bt.BackgroundColor = Colors.Transparent;else bt.BackgroundColor = Colors.LightPink;
    }

C# code - MainPage:

public partial class MainPage : ContentPage
{
    public MainPage()
    { 
        InitializeComponent();
        Chld.Add("Button1");
        Chld.Add("Button2");
        Chld.Add("Button3");
    } 
}`

XAML code :

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:MauiButton"
             x:Class="MauiButton.MainPage">
      <local:Page1 x:Name="Chld"></local:Page1>
</ContentPage>

Works on Windows Machine. On a phone (Android) without ArrangeOverride too. But if I add ArrangeOverride, the buttons are visible, but the Clicked event (OnButtonClicked) doesn't fire. Nothing happens when the button is clicked.

Does anyone know how to solve that please ?

Thanks.


Ответы (0 шт):