如何绑定Command的快捷键到上下文

 
   插件开发过程中,我们有时会需要在一个特定上下文中使用快捷键,这样就需要使用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:
  1.          <extension
  2.             point="org.eclipse.ui.contexts">
  3.             <context
  4.                name="Pattern Test ViewScope"
  5.                description="The context of PatternTestView"
  6.                 id="com.myplugin.core.ui.views.PatternTestView.viewScope"
  7.                parentId="org.eclipse.ui.contexts.window">
  8.             </context>
  9.          </extension>  
    2)为com.myplugin.core.ui.views.PatternTestView.viewScope上下文绑定TestRegularAction,在PatternTestView的createPartControl方法结尾处添加下面一段代码:
  1.         IContextService contextService = (IContextService) getSite().getService(IContextService.class);
  2.         contextService.activateContext(VIEW_CONTEXT_ID);
  3.         TestRegularAction testRegularAction = new TestRegularAction();
  4.         IHandlerService service = (IHandlerService) getViewSite().getService(IHandlerService.class);
  5.         service.activateHandler(testRegularAction.getActionDefinitionId(), new ActionHandler(testRegularAction));
    3)将TestRegularAction与Ctrl+Enter快捷键绑定,先在插件的plugin.xml加入如下内容:
  1.   <extension
  2.         point="org.eclipse.ui.commands">
  3.      <command
  4.            id="com.myplugin.core.testRegular" <!--此处定义Command ID,将会设置为TestRegularAction的ActionDefinitionId-->
  5.            name="testRegular">
  6.      </command>
  7.   </extension>
  8.   <extension
  9.         point="org.eclipse.ui.bindings">
  10.      <key
  11.            commandId="com.myplugin.core.testRegular"
  12.            contextId="com.myplugin.core.ui.views.PatternTestView.viewScope"<!--此处contextID即为PatternTestView中已经定义的上下文ID-->
  13.            schemeId="org.eclipse.ui.defaultAcceleratorConfiguration"
  14.            sequence="Ctrl+Enter"><!--需要绑定的快捷键-->
  15.      </key>
  16.   </extension>
       再为TestRegularAction设置ActionDefinitionId,也即上段代码中定义的commandID,在TestRegularAction的构造函数中加入如下代码:
  1. setActionDefinitionId("com.myplugin.core.testRegular");
   至此,我们已成功将Ctrl+Enter快捷键绑定到PatternTestView上下文中。只要焦点移到PatternTestView上,键盘上同时按下Ctrl+Enter键,便会立刻执行TestRegularAction的run方法。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值