RSS

Search Engine

Wednesday, June 16, 2010

Enabled when (visible when)

The command framework allows to restrict the availability and visibility of commands, handlers and ui contributions via the core expressions .

In this example we want the command only be enabled if one item from a list of items is selected.

Create a new project "de.vogella.rcp.commands.enable" based on the "RCP application with a view" example.

Add a command with the ID "de.vogella.rcp.commands.enable.command". Add this command to the menu and the toolbar and create the following default handler.

   
package de.vogella.rcp.commands.enable.handler;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.ui.handlers.HandlerUtil;

public class Command extends AbstractHandler {

@Override
public Object execute(ExecutionEvent event) throws ExecutionException {
MessageDialog.openInformation(HandlerUtil.getActiveWorkbenchWindow(
event).getShell(), "Info", "Info for you");

return null;
}

}

Select plugin.xml and add "org.eclipse.core.expressions" as a dependency. Select then the Extensions tab and add the extensions org.eclipse.core.expressions.definitions.

Using right mouse click add a definition "oneElementSelected". Add a "with" variable "selection".

Tip

"selection" is a predefined variable which will be calculated automatically by Eclipse. See core expressions for additional variables you can use. For example for a popup menu "activeMenuSelection" provides the selection.

On the "activeMenuSelection" right mouse click and add a count with the value "1". The result should look like

On your handler, right mouse click and select enabledWhen. Right mouse click and add a "reference" to it with the value "oneElementSelected". The result should look like.

The expression were are using is based on "selection". Therefore the list must register itself as selection provider to inform the workbench in case something is selected. Therefore add "getSite().setSelectionProvider(viewer);" in createPartControl of View.java.

   
public void createPartControl(Composite parent) {
viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL
| SWT.V_SCROLL);
viewer.setContentProvider(new ViewContentProvider());
viewer.setLabelProvider(new ViewLabelProvider());
viewer.setInput(getViewSite());
// Makes the selection available to the workbench
getSite().setSelectionProvider(viewer);
}

If you now run the application your command should only be enabled if one element in the list is selected.

Tip

You can also only display the menu if one item is selected. The approach is the same but you only define the restriction on the menu contribution directly (visible when on the command in the menu). For a command in the toolbar the definition would look like:

0 comments:

Post a Comment