开发者

Binding a Method to an Event in C# with += operator

I was making a windows form, and I was trying to manually bind a method to the click event of myButton, like this:

    public Form1()
    {
        InitializeComponent();
        myButton.Click = new EventHandler(ShowMessage("You clicked my button!"));
    }

    private void ShowMessage(string message)
    {
        MessageBox.Show(message);
    }

As some of you might guess, the compiler didn't like this. I wasn't sure why, because I am used to being able to do things in Javascript like this:

document.getElementById("myButton").onclick = function(){showMessage("You clicked my button")};
function showMessage(message) {
  alert(message);
}

I muddled through it and eventually ended up doing something really ugly involving a global variable like this:

    string message = "";
    public Form1()
    {
        InitializeComponent();
        message = "You clicked my button!";
        myButton.Click += ShowMessage; 
    }

    private void ShowMessage(object sender, EventArgs e)
    {
        MessageBox.Show(message);开发者_如何学Python
    }

Here are my two questions: first, is there a cleaner way to do this? Second, why do event methods have to be assigned with a += and not just an =?


Event handlers must be added to events with += because the event may have multiple other delegates unknown to your particular piece of code. Pure assignment would imply an ability to remove other associated delegates, something you should not have permission to do as a client of the event.

Additionally, you probably want to take advantage of anonymous delegates to accomplish any form of argument binding. For example:

myButton.Click += delegate(object sender, EventArgs e) {
    MessageBox.Show("You clicked my button!");
};


You can use also lambda.

myButton.Click += (sender, e) => {
    MessageBox.Show("You clicked my button!");
};


Here are my two questions: first, is there a cleaner way to do this?

yes anonymous functions, just like in JavaScript (other syntax)

myButton.Click += delegate(object sender, EventArgs e)   
{ 
  MessageBox.Show(message);
};  

why do event methods have to be assigned with a += and not just an =?

Else you can have only 1 eventhandler instead of multiple ones to the same event. += is used a lot in programming language to add something. = is used to set the variable to a value.


You can type myButton.Click += delegate { showmessage("You clicked my button!"); };


Because more than one handler can be added, were as in your javascript code, only one function will be called in onclick.

Example:

myButton.Click += ShowMessage;
myButton.Click += LogToFile;

Both functions ShowMessage and LogToFile would get called when a button click happens. This is what the "+" in "+=" is trying to indicate. You're adding to the handler, not replacing it.

As far as making it easier, you would use anonymous lamdas to help like, but note that it makes it harder to detach/remove the handlers later (if thats important).

myButton.Click += new EventHandler( (sender,e) => ShowMessage("You clicked my button!") );


Try this solution to get around the need of a global variable, with the possibility of having a named, reusable method for your event handler:

private void ShowMessage(object sender, EventArgs e, string message)
{
    MessageBox.Show(message);
}


public Form1()
{
    InitializeComponent();
    myButton.Click += delegate(object sender, EventArgs e)   
    { 
        ShowMessage(sender,e,"You clicked my button!");
    };  
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜