How to assign click event

131,451

Solution 1

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

private void btn1_Click(object sender, RoutedEventArgs e)
{
    // do something
}

Solution 2

The following should do the trick:

btn.Click += btn1_Click;

Solution 3

// 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);
}

Solution 4

I don't think WPF supports what you are trying to achieve i.e. assigning method to a button using method's name or btn1.Click = "btn1_Click". You will have to use approach suggested in above answers i.e. register button click event with appropriate method btn1.Click += btn1_Click;

Share:
131,451

Related videos on Youtube

KMC
Author by

KMC

Tutorials: WPF C# Databinding C# Programming Guide .NET Framework Data Provider for SQL Server Entity Framework LINQ-to-Entity The Layout System Resources: LifeCharts: free .NET charts FileHelper: text file helper cmdow

Updated on July 09, 2022

Comments

  • KMC
    KMC almost 2 years

    I have an array of button which is dynamically generated at run time. I have the function for button click in my code, but I can't find a way to set the button's click name in code. So,

    what is the code equivalent for XAML:

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

    Or, what should I place for "????" in the following Code:

    Button btn = new Button();
    btn.Name = "btn1";
    btn.???? = "btn1_Click";
    
  • user189728
    user189728 over 5 years
    Why does it use +=? Do buttons contain more than one click event?
  • Gaboik1
    Gaboik1 over 5 years
    @user189728 This is the way the Event system works in .NET, you can subscribe multiple 'handlers' to any event. You can almost think of an event as a class that has overridden the += operator and it essentially appends a callback to a queue.
  • StayOnTarget
    StayOnTarget over 3 years
    Yes, any event can have more than one handler (function callback if you want to think of it that way)