所有自定义按钮/MAUI .NET8 的 C# 代码中的单个事件处理程序

问题描述 投票:0回答:1

简单的内容页面,上面有很多按钮。 我想要一个事件处理程序 (

OnButtonPress
) 来解码按下了哪个按钮并采取各种操作。 我没有在 XAML 中繁琐地编写
Clicked="OnButtonPress"
一百次,而是想(因为出于不同的原因,我无论如何都定义了一个自定义 Button2:Button 类)将此事件处理程序定义为 Button2 类的标准。

有办法做到这一点吗? 我已经搜索和 AI 了好几天了,似乎无法弄清楚这个问题,所以希望得到指点。

我已经尝试过:

  • <Style />
    ,但事件不可绑定。
  • 在Button2类中添加
    public EventHandler Clicked = "OnButtonPress"
    ,但不能将类型String隐式转换为System.EventHandler。
  • this.Clicked += new EventHandler(MainPage.OnButtonPress);
    放入 Button2 类中,但它抱怨
    OnButtonPress
    在 MainPage 中不存在,而它显然存在。
  • OnButtonPress
    移动到 Button2 类中,但随后它抱怨“无法找到 OnButtonPress 的类型或命名空间”(就像......就在那里,伙计)。
  • this.Clicked = OnButtonPress();
  • this.Clicked += OnButtonPress(object sender, EventArgs e);

代码的总体结构很简单:

namespace Adam
{
  public partial class MainPage : ContentPage
  {
    public void OnButtonPress(object sender, EventArgs e)
    {
      // decoding stuff goes here
    }

    public class Button2 : Button
    {
      // lotsa properties and stuff added here

      public Button2()
      {
        // I didn't put any code in here
      }
    }
  }
}

和 XAML(我省略了所有网格和其他内容):

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:Adam"
             x:Class="Adam.MainPage" 
             BackgroundColor="Black">
  <local:Button2 Text = "Test" />
>

c# event-handling overriding maui
1个回答
0
投票

我正在用C#进行设计部分,但是你可以根据XAML代码来组织它。在App.cs文件中定义静态函数后,您可以从所有页面访问该函数。如果你很难做到这一点,你可以在每个使用按钮的页面中创建一个函数,并将这个函数写在命令部分。

public partial class App : Application
{

    public static void btn1Cmd()
    {
        // Command
    }

    public App()
    {
        InitializeComponent();
    }
}
                                new Button()
                                {
                                    Text = "Kayıt Ol",
                                    BackgroundColor = Colors.Transparent,
                                    TextColor = Color.FromHex("#4A9EF7"),
                                    FontSize = 16,
                                    Padding = 1,
                                    Margin = 1,
                                    FontFamily = "dmsansMedium",
                                    *Command = new Command(App.btn1Cmd),*
                                },
© www.soinside.com 2019 - 2024. All rights reserved.