[英]How to add a command to an editor context menu in Eclipse only if text is selected
仅当文本标记为选中时,我才想向 eclipse 上下文菜单添加一个项目
下面是我的 XML 相关片段:
<menuContribution
allPopups="false"
locationURI="popup:org.eclipse.ui.popup.any">
<command
commandId="com.test.ide.menu.commands.sampleCommand"
icon="icons/sample.png"
id="com.test.ide.menu.toolbars.sampleCommand"
tooltip="Popup test">
<visibleWhen>
<with variable="selection">
<instanceof value="org.eclipse.jface.text.ITextSelection"/>
</with>
</visibleWhen>
</command>
</menuContribution>
我尝试了如何为 Eclipse 中的编辑器上下文菜单提供命令中的解决方案,但无法解决问题
我错过了什么?
你能帮我吗?
谢谢
阿夫纳
问题是编辑器通常总是有一个文本选择集 - 如果没有选择任何字符,它将只是零长度。
我看不到使用现有表达式对此进行测试的方法,因此可能需要使用org.eclipse.core.expressions.propertyTester
扩展点定义您自己的属性测试器。
<extension
point="org.eclipse.core.expressions.propertyTesters">
<propertyTester
class="tested.TextSelectedPropertyTester"
id="tested.propertyTester1"
namespace="tested"
properties="textSelected"
type="org.eclipse.jface.text.ITextSelection">
</propertyTester>
</extension>
像这样使用:
<visibleWhen>
<with variable="selection">
<adapt type="org.eclipse.jface.text.ITextSelection">
<test
property="tested.textSelected">
</test>
</adapt>
</with>
</visibleWhen>
属性测试器非常简单:
public class TextSelectedPropertyTester extends PropertyTester
{
@Override
public boolean test(Object receiver, String property, Object [] args, Object expectedValue)
{
if (receiver instanceof ITextSelection textSel) {
return textSel.getLength() > 0;
}
return false;
}
}
请注意, if
语句使用 Java 16 instanceof 类型模式,如果您需要使用较旧的 Java 运行,请使用:
if (receiver instanceof ITextSelection) {
return ((ITextSelection)receiver).getLength() > 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.