开发者

Set up single event handler for multiple buttons in .NET?

开发者 https://www.devze.com 2023-01-24 09:30 出处:网络
An application I\'m writting in silverlight/c# consists of 13 permanent buttons that when clicked perform a simple navigation to another page.

An application I'm writting in silverlight/c# consists of 13 permanent buttons that when clicked perform a simple navigation to another page.

The problem is my code behind has 13 different event handlers(alot of code) for a nearly identical purpose.

Is there 开发者_如何学JAVAa way to detect which button was pressed so that a single event handler gets fired, and a simple if statement within could determine which page to go to?


yes: you can use the same method for all buttons, and use the parameter "sender" as "sender.Name" to get the name of the pressed button.


In the designer code of your program, tack on the same event handler for all 13 buttons (look for the code that has += and put the same event handler for all of them).

Notice that the event handler has an object (s) parameter. You can use this parameter as follows:

if(s.Name = "Button1") {//button 1 stuff}

else if (s.Name = "Button2") {button 2 stuff}

etc..

EDIT: should have been s.Name = "Button1, 2, 3, etc.."


Test the sender parameter of the button click event handler - you'll be able to test which button was the sender.


Use a Dictionary using 'sender' as key. The 'value' could be the page to navigate to.


If you have lots of code in your event handler you should break that out to a separate method anyway and send the button specific parameters to that method.

But you can still have one event handler if you look at the sender argument.

0

精彩评论

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