0

I am new to C# and OOP, and still trying to wrap my mind around that. Watched a lot of tutorials, and somethings i do understand, other not so much...

Anyway, I am trying to give myself problems, and then solve them.

Here is the problem.

I know how to create some control on WPF during runtime:

private void addButton()
    {

        for (int i = 0; i < 10; i++)
        {

        var btnX = new Button { Content = "btn" + i };

        btnX.Click += ClickHandler1;

        stPanel.Children.Add(btnX);
        }
    }

But, now I would like this method to exist in separated class which can be called from another class, passed some arguments, and then create buttons in the class that passed arguments.

So in my Programs.cs now I have:

  private void addButtonX()
    {

        for (int i = 0; i < 10; i++)
        {

            CreateGroupButtons btn = new CreateGroupButtons();
            stPanel.Children.Add(btn.addButton(i));
        }
    }

I have Class:

 class CreateGroupButtons
{

    public Button addButton(int num)
    {
         var btnX = new Button { Content = "btn" + num };

                   return btnX; 

    }
}

And the buttons are created, but now there is just one more problem, and i am not sure how to fix that:

How to add Handler event?

btnX.Click += ClickHandler1;

Thank you!

1 Answer 1

2

I assume you are using the System.Windows.Controls.Button class? If so, ButtonBase which is the base class that Button derives from, defines an event named Click. To add the event handler, you can just subscribe to this event.

btnX.Click += (sender, args) => { /* Your code here */ }

Update

If you want the addButton method to subscribe to a method outside this method, you can send in an Action which can be triggered inside the event handler

public Button AddButton(int num, Action actionToPerform)
{
    var btnX = new Button { Content = "btn" + num };
    btnX.Click += (sender, args) => { actionToPerform(); }
    return btnX; 
}

and then from outside

var btns = new CreateGroupButtons()
btns.AddButton(1, () => { MessageBox.Show("Hello, World"); }; );
Sign up to request clarification or add additional context in comments.

1 Comment

Glad I would help, @Bodul :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.