如何在代码后面添加带Children.Add的按钮?如何添加点击按钮

How to add button with Children.Add in code behind?How to add clicked to button

在堆栈布局中添加按钮没有给我添加按钮名称的位置。

var sl = new StackLayout
            {
                Children = {
                    new Button {Text="Click Me"},
}
};

如何为按钮添加名称以便添加 button.clicked 事件?

使用普通的 C# 对象引用

Button button;

var sl = new StackLayout
{
  Children = {
    (button = new Button {Text="Click Me"})
  }
};

button.Clicked += MyClickedHandler;
XAML中的

x:Name并不是一个实际的对象属性,它只是为了方便XAML工具生成一个对象引用。

How to add button with Children.Add in code behind?How to add clicked to button

要将按钮添加到页面并在后面的代码中将点击事件添加到按钮,请尝试以下代码:

Button button = new Button
{
    Text = "Button",
    VerticalOptions = LayoutOptions.CenterAndExpand,
    HorizontalOptions = LayoutOptions.Center
};
button.Clicked += Click_Event;

Content = new StackLayout
{
    Children =
    {
        button
    }
};

private void Click_Event(object sender, EventArgs e)
{
    throw new NotImplementedException();
}

教程:
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/button#creating-a-button-in-code

How do I add a name to the button so I can add the button.clicked event?

x:Name 属性用于 xaml 而不是代码隐藏。
检查文档:
https://docs.microsoft.com/en-us/xamarin/xamarin-forms/xaml/xaml-basics/get-started-with-xaml?tabs=windows#xaml-and-code-interactions