0

How do i create a new button on a stackpanel perhaps in a class file

 public static void addbtn()
    {
        Page1 p1 = new Page1();
        Button btn = new Button();
        p1.stackPanel1.Children.Add(btn);
    }

I'm sure this isnt really right, at the same time how do i give it a event handler.

My objective is to create a button on form1 with a click of a button from form2.

Please help me with this. Thank you!

2
  • In WPF you rarely ever want to create controls in code, usually you would only manipulate data and let the UI be created via data templating. Commented Mar 5, 2012 at 18:57
  • probably shouldn't be doing it in a static method.. Commented Mar 5, 2012 at 18:58

2 Answers 2

1

Your code should work. You can add properties/events to Button like:

Button btn = new Button();
btn.Content = "Press me";
btn.Click = (sender, e) => { *your handling code* };
Sign up to request clarification or add additional context in comments.

1 Comment

Its not maybe because of Page1 p1 = new Page1();
1

You are adding your button to the Page1 object you just created which, presumably, is not the one that is being shown to the user.

If you are in the same class that defines Page1 itself you can simply use

this.stackpanel1.children.add(btn)

Although note this would have to be an instance method not a static method, otherwise it won't know what "this" refers to.

If this is not the same class, then you will have to pass it a reference to the object you are trying to add the button to. Something like this:

public static void addbtn(Page1 p1)
{
    Button btn = new Button();
    p1.stackPanel1.Children.Add(btn);
}

And you'll pass in the actual instance of Page1 you want to add the button to.

2 Comments

Class1.addbtn(??); how do i add from form2?
So let me get this straight, you want a function in form2 to add a button to form1? Is that correct? If so, then form2 will need a reference to form1 and you'll either need to make the stack panel you are adding to a public property of form1 or you need a public instance method (not static) in form1 you can call from form2.

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.