插件开发过程中,我们有时会需要在一个特定上下文中使用快捷键,这样就需要使用Command的绑定技术。举例说明:假如有这样的一个需求,我有个 View(暂且叫PatternTestView,继承自org.eclipse.ui.part.ViewPart),现在需要当焦点在 PatternTestView上时,按下Ctrl+Enter便可以执行TestRegularAction(继承自 org.eclipse.jface.action.Action)命令。现在我们来一步步实现这个需求:
1)先在plugin.xml中为PatternTestView定义一个上下文com.myplugin.core.ui.views.PatternTestView.viewScope:至此,我们已成功将Ctrl+Enter快捷键绑定到PatternTestView上下文中。只要焦点移到PatternTestView上,键盘上同时按下Ctrl+Enter键,便会立刻执行TestRegularAction的run方法。
2)为com.myplugin.core.ui.views.PatternTestView.viewScope上下文绑定TestRegularAction,在PatternTestView的createPartControl方法结尾处添加下面一段代码:
- <extension
- point="org.eclipse.ui.contexts">
- <context
- name="Pattern Test ViewScope"
- description="The context of PatternTestView"
- id="com.myplugin.core.ui.views.PatternTestView.viewScope"
- parentId="org.eclipse.ui.contexts.window">
- </context>
- </extension>
3)将TestRegularAction与Ctrl+Enter快捷键绑定,先在插件的plugin.xml加入如下内容:
- IContextService contextService = (IContextService) getSite().getService(IContextService.class);
- contextService.activateContext(VIEW_CONTEXT_ID);
- TestRegularAction testRegularAction = new TestRegularAction();
- IHandlerService service = (IHandlerService) getViewSite().getService(IHandlerService.class);
- service.activateHandler(testRegularAction.getActionDefinitionId(), new ActionHandler(testRegularAction));
再为TestRegularAction设置ActionDefinitionId,也即上段代码中定义的commandID,在TestRegularAction的构造函数中加入如下代码:
- <extension
- point="org.eclipse.ui.commands">
- <command
- id="com.myplugin.core.testRegular" <!--此处定义Command ID,将会设置为TestRegularAction的ActionDefinitionId-->
- name="testRegular">
- </command>
- </extension>
- <extension
- point="org.eclipse.ui.bindings">
- <key
- commandId="com.myplugin.core.testRegular"
- contextId="com.myplugin.core.ui.views.PatternTestView.viewScope"<!--此处contextID即为PatternTestView中已经定义的上下文ID-->
- schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
- sequence="Ctrl+Enter"><!--需要绑定的快捷键-->
- </key>
- </extension>
- setActionDefinitionId("com.myplugin.core.testRegular");