[英]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.