开发者

Make a customized widget observable?

I had create a simple keywords highlighting editor, it just wrap a StyledText widget:

public class SQLSegmentEditor extends Composite {

    private StyledText st;

    public SQLSegmentEditor(Composite parent) {
        super(parent, SWT.NONE);
        this.setLayout(new FillLayout());
        st = new StyledText(this, SWT.WRAP | SWT.BORDER | SWT.V_SCROLL);
        st.addLineStyleListener(new SQLSegmentLineStyleListener());
    }

}

How can I make it can be used in data-binding? I am looking for the proper way, not just one that makes it work.

I want to observer the text content of the inner StyledText.

For example : I can just add a getStyledText method to return the wrapped StyledText widget for using it in databinding. But this will take a risk. In order to keep my editor behavior correctly, I should keep the StyledText开发者_开发百科 widget not visible to client code.


Although I don't understand your argument of not exposing the wrapped widget to the client, here is a possible solution. The widget can provide a WritableValue that can be bound directly via databinding by the client. That means the binding goes over 3 parties: the clients target, the wrapping writable-value and the SWT source. The only drawback is that you have a direct dependency to Databinding in your widget. Here is a snippet.

import org.eclipse.core.databinding.DataBindingContext;
import org.eclipse.core.databinding.observable.value.WritableValue;
import org.eclipse.jface.databinding.swt.ISWTObservableValue;
import org.eclipse.jface.databinding.swt.WidgetProperties;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;

public class SQLSegmentEditor extends Composite {

    private final StyledText st;

    private final WritableValue value = new WritableValue();

    public SQLSegmentEditor(Composite parent, DataBindingContext ctx) {
        super(parent, SWT.NONE);
        assert ctx != null;
        setLayout(new FillLayout());
        st = new StyledText(this, SWT.WRAP | SWT.BORDER | SWT.V_SCROLL);
        ISWTObservableValue swtBinding = WidgetProperties.text(SWT.Modify)
                .observe(st);
        ctx.bindValue(value, swtBinding);
    }

    public WritableValue getValue() {
        return value;
    }
}

So the client code would look like:

DataBindingContext ctx = new DataBindingContext();
SQLSegmentEditor sqlSegmentEditor = new SQLSegmentEditor(getParent(), ctx);
IObservableValue modelObservable = //setup my model-observable
ctx.bindValue(modelObservable, sqlSegmentEditor.getValue());
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜