简体   繁体   English

单击该行时,设置CheckboxTreeViewer的复选框

[英]Set the checkbox of a CheckboxTreeViewer when the row is clicked

I'm looking for a generic approach to check the checkbox of CheckBoxTreeViewer, when the row / the item is selected. 当选择行/项目时,我正在寻找一种通用方法来检查CheckBoxTreeViewer的复选框。 I've found a similar question regarding the CheckBoxTableViewer, which answer helped me, but it doesn't apply to the CheckBoxTreeViewer. 我发现了 CheckBoxTableViewer 类似的问题 ,该问题对我有帮助,但不适用于CheckBoxTreeViewer。 I assume, I have to use the ISelectionChangedListener. 我想,我必须使用ISelectionChangedListener。

You can add an ISelectionChangedListener and receive the selected object from the SelectionChangedEvent. 您可以添加ISelectionChangedListener并从SelectionChangedEvent接收选定的对象。 Then you can set the checked state for this object like this: 然后,您可以为该对象设置检查状态,如下所示:

viewer.addSelectionChangedListener(new ISelectionChangedListener() {
        @Override
        public void selectionChanged(SelectionChangedEvent event) {
            Object selection = ((StructuredSelection)event.getSelection()).getFirstElement();
            viewer.setChecked(selection, true);
        }
    });

I solved the problem with the grayed state by calling the CheckStateListener, which is responsible to maintain the checked and grayed state of the elements. 我通过调用CheckStateListener解决了灰色状态的问题,该方法负责维护元素的选中状态和灰色状态。

public void selectionChanged(final SelectionChangedEvent event) {
    Object selection = ((StructuredSelection) event.getSelection()).getFirstElement();
    if (selection != null) {
        boolean state = !checkboxTreeViewer.getChecked(selection);
        checkboxTreeViewer.setChecked(selection, state);
        checkboxTreeViewer.setSelection(StructuredSelection.EMPTY);
        checkStateListener.checkStateChanged(new CheckStateChangedEvent((ICheckable) event.getSource(), selection,
            state));
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM