how to use delegate to enable / disable mainmenu from another class

  • Thread starter Thread starter AboutJAV
  • Start date Start date
A

AboutJAV

I created a mainmenu in the form class. I added the following code

public delegate void ChangeMainMenuDelegate(bool bState);

public void ChangeMainMenuState(bool bState)
{
for (int n = 0; n < mainmenu.menuitems.count; n++)
{
mainmenu.menuitems[n].Enabled = bState;
}

}

I want to call the delegate from another class (View class)

How do I do this?

Thanks
 
You don't call a delegate, a delgate is a way to define the way a method
should be for an event.

So


public delegate void ChangeMainMenuDelegate(bool bState);
public event ChangeMainMenuDelegate myEvent;

then outside classes can hook the event like so: (.net 2 syntax)

myEvent += OnEventRaised;

public void OnEventRaised(bool bState) //notice it matches the params of the
delegate as it must (bool param)
{
//so when that event is fired in the class it is in this method will
also be fired
}


Make sense?
 
Hi,

IIRC, you only need to set the Enabled property on the containing menu and
the menu's items will inherit the value, so looping isn't required.

To invoke a delegate you need a reference to an instance of the delegate and
then you can call the Invoke method:

ChangeMainMenuDelegate method = new
ChangeMainMenuDelegate(ChangeMainMenuState);
method.Invoke(true);

or the preferred 2.0 syntax with inference, as Daniel mentioned:

ChangeMainMenuDelegate method = ChangeMainMenuState;
method.Invoke(true);

However, you don't need a delegate if its target is in scope. In that case,
just call the target method directly:

view.ChangeMainMenuState(true);

(assuming "view" is an instance of the class that defines the
ChangeMainMenuState method)
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Back
Top