Elegant way to reuse a method handler

  • Thread starter Thread starter Tim Jarvis
  • Start date Start date
T

Tim Jarvis

Hi,

I am using a toolbar object that has a number of buttons that generally
speaking have a corresponding menu item. What I was hoping to be able
to do was to write an event handler for the menu item and assign it to
the click event of the toolbar button.

But I find that the toolbar buttons don't have a click event at all, I
have to write a handler in the buttonclick event of the toolbar itself
which in turn gets a ToolbarButtonClickEventArgs param passed that I
can use to determine which button was clicked. Which leads to code like
the following

if (e.Button == btnSomething)
{
mnuSomthing_Click(this,EventArgs.Empty);
}
else
{
if (e.button == btnSomethingElse)
{
mnuSomthingElse_Click(this,EventArgs.Empty);
}
}

Surely there is a better way than this...surely.

Cheers Tim.
 
Tim,

There are number of ways that can be termed as "better". Some may be an
overkill given the situation at hand.

Lets say you had a class that takes a certain delegate type as a parameter
in their constructor. This delegate instance is the actual method you'd like
each instance to "call".

You stuff instances of these classes into a hash table using the name of the
button as the key (identifier).

So the code in your event would look like this

ht.Add(xxxButton.Name, new MyObject(new
SomeDelegate(TheActualMethodForThisButton)));
and so on for each button you have.

Then in the buttonclick event

((MyObject)ht[e.Button.Name]).Execute(this, EventArgs.Empty);

Where MyObject is the class type that has an Execute method whose
implementation in turn calls the delegate passed to it in the constructor.


I hope you get the picture. Also, I don't know if "Button" has a Name
property, but any other "identifier" will do.
 
Shiv Kumar wrote:

I hope you get the picture. Also, I don't know if "Button" has a Name
property, but any other "identifier" will do.

mmm, interesting approach. I'll look at this in more detail.

Cheers Tim.
 
Probably a simpler solution (one that is more fitting for this job) is to
simply stuff the delegate into the hashtable, rather than have an object
that has a method that calls a delegate etc.
 
Back
Top