WPF按钮单击C#代码

KMC*_*KMC 18 c# wpf xaml event-handling

我有一个按钮数组,它在运行时动态生成.我的代码中有按钮单击功能,但我找不到在代码中设置按钮的单击名称的方法.所以,

什么是XAML的等效代码:

<Button x:Name="btn1" Click="btn1_Click">

或者,我应该为"????"放置什么 在以下代码中:

Button btn = new Button()
btn.Name = "btn1";
btn.???? = "btn1_Click";

Tom*_*eld 41

Button btn = new Button();
btn.Name = "btn1";
btn.Click += btn1_Click;

private void btn1_Click(object sender, RoutedEventArgs e)
{
    // do something
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*rth 11

以下应该做的伎俩:

btn.Click += btn1_Click;
Run Code Online (Sandbox Code Playgroud)


abr*_*pin 5

// sample C#
public void populateButtons()
{
    int xPos;
    int yPos;

    Random ranNum = new Random();

    for (int i = 0; i < 50; i++)
    {
        Button foo = new Button();
        Style buttonStyle = Window.Resources["CurvedButton"] as Style;

        int sizeValue = ranNum.Next(50);

        foo.Width = sizeValue;
        foo.Height = sizeValue;
        foo.Name = "button" + i;

        xPos = ranNum.Next(300);
        yPos = ranNum.Next(200);

        foo.HorizontalAlignment = HorizontalAlignment.Left;
        foo.VerticalAlignment = VerticalAlignment.Top;
        foo.Margin = new Thickness(xPos, yPos, 0, 0);

        foo.Style = buttonStyle;

        foo.Click += new RoutedEventHandler(buttonClick);
        LayoutRoot.Children.Add(foo);
   }
}

private void buttonClick(object sender, EventArgs e)
{
  //do something or...
  Button clicked = (Button) sender;
  MessageBox.Show("Button's name is: " + clicked.Name);
}
Run Code Online (Sandbox Code Playgroud)