Is there a type of object that I can use both Buttons AND MenuItems to access their Tag properties?

I want both MenuItems and Button controls to be bound to the type of object whose tag property I can reference.

Is there such a type of object?

eg.

void itemClick(object sender, EventArgs e)
{
    Control c = (Control)sender;
    MethodInvoker method = new MethodInvoker(c.Tag.ToString(), "Execute");
    method.Invoke();
}

      

Also it fails - "Unable to use object type" System.Windows.Forms.MenuItem "to enter" System.Windows.Forms.Control "

What can replace Control in this example?

+1


source to share


4 answers


Use the "how" operator.

object tag;
Button button;
MenuItem menuItem = sender as MenuItem;
if (menuItem  != null)
{
    tag = menuItem.Tag;
}
else if( (button = sender as Button) != null )
{
    tag = button.Tag;
} 
else 
{
    //not button nor MenuItem 
}

      



code>

+2


source


I am writing this without an IDE.




object myControlOrMenu = sender as MenuItem ?? sender as Button;
if (myControlOrMenu == null)
// neither of button or menuitem

      

+2


source


the inheritance path is different for MenuItem and Button, there is no shared / inherited Tag property.

MenuItem inherits from a menu that declares a tag property, Button Inherits from Control, which also implements the Tag property. You should be able to display both the MenuItem and the Button to Component, but that won't help you, since the Tag property is declared in the derived classes I mentioned (menu and control).

In this particular case, you probably need to use reflection rather than inheritance. Or come up with a plan B

+1


source


Management is what you are looking for.

0


source







All Articles