Domanda

I have a menu item XYZ. I have a preference page MyPref which has a check box and a couple of text fields. When the check box in MyPref is check, I want menu XYZ to be enabled else it should be disabled. Is there a way to achieve this.

È stato utile?

Soluzione

Yes, the way certainly exist.

1). Create an entry in your IPreferenceStore - just get the class which extends AbstractUIPlugin and do the following:

IPreferenceStore store = IExtendAbstractUIPlugin.getDefault()
      .getPreferenceStore();

then store some value which will reflect your checkbox state:

preferenceStore.setValue("XYZMenuPreference", false); // if disabled

or

preferenceStore.setValue("XYZMenuPreference", true); // if enabled

2). Create a Property Tester extention to your plugin.xml:

<extension point="org.eclipse.core.expressions.propertyTesters">
  <propertyTester
     class="org.xyz.PropertyTester"
     id="org.xyz.PropertyTester"
     type="java.lang.Object"
     namespace="org.xyz"
     properties="XYZmenu">
  </propertyTester>
</extension> 

3). When declaring your menu handler in plugin.xml you should add the following:

<handler
 class="your-menu-handler-class"
 commandId="your-command-id">
     <enabledWhen>
     <with variable="selection">                    
     <test property="org.xyz.XYZmenu" value="true" forcePluginActivation="true"/> 
     </with> 
     </enabledWhen>           
</handler>

4). Now you need a class "org.xyz.PropertyTester" (as defined in plugin.xml) which will extend the org.eclipse.core.expressions.PropertyTester and override method test(<some args>) where he must check the property value:

if (property.equals("XYZmenu"){
   IPreferenceStore store = IExtendAbstractUIPlugin.getDefault()
                    .getPreferenceStore();
   return store.getBoolean("XYZMenuPreference");
}

5). After that add a change listener to your checkbox and use it to re-evaluate a visibility of your menu item:

IEvaluationService service = (IEvaluationService) PlatformUI
   .getWorkbench().getService(IEvaluationService.class);
service.requestEvaluation("org.xyz.XYZmenu");

it will force the method test() from your org.xyz.PropertyTester class to be called and will enable your menu item if preference "XYZMenuPreference" is set to true.

upd.

namespace - a unique id determining the name space the properties are added to
properties - a comma separated list of properties provided by this property tester

this is from official eclipse tutorial so you can feel free to define any namespace and property name, but the you should use it like in point 5.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top