Enable menus by binding to a window's visibility

Hello,

I use my main window’s isVisible() instance variable to enable or disable menus items. I bind the menu item to my gWindow property in IB by putting “gWindow.visible” into the enable field of the menu item. If I want the reverse result, I add a NSNegateBoolean.

If I want that the user can open only one file at a time, for example, I enable “New”, “Open”. when the window is hidden, or I enable “Close” when it’s visible.

So far, so good.

But this does not work if I want to enable/disable the menu as a whole (i.e. the menu’s title). The menu stays disabled, the visibility of the window doesn’t matter.

An explanation?

Hi,

the proper method to en-/disable menu items dynamically is validateMenuItem: of NSMenuValidation Protocol.
It’s always called when the user is going to open a menu and returns the “shouldBeEnabled” state of each menu item.
For example (Cocoa code). I


- (BOOL)validateMenuItem:(NSMenuItem *)item {
	
    if ([item action] == @selector(newDocument:) || [item action] == @selector(openDocument:) )
        return YES;
	
	else if ([item action] == @selector(performClose:) )
		return [window isVisible];
	else
		return [item action] != nil;
}


PS: A document based application does a lot of things you’re dealing with for free.

I KNOW! :slight_smile: But I’m not making a “TextEdit 2” application, and I read about NSDocument – where would be a lot to adapt in that case too.

Thank you for the tip, I’ll have a look at this NSMenuValidation. And I’ll be watching to not fight the frameworks :wink:

Regards,