我正在使用JFace数据绑定框架将复选框选择与模型链接:
final DataBindingContext ctx = new DataBindingContext();
final Realm realm = ctx.getValidationRealm();
final IViewerObservableValue selection = ViewersObservables.observeSingleSelection(viewer);
final IObservableValue selectionObservable = BeansObservables.observeDetailValue(realm, selection, "isSelected", boolean.class);
final UpdateValueStrategy strategy = new UpdateValueStrategy(true, UpdateValueStrategy.POLICY_UPDATE);
ctx.bindValue(SWTObservables.observeSelection(button), selectionObservable, strategy, strategy);
演示文稿需要使用复选框的文本来显示有关当前选择的特定信息,但是不能使用
observeText(Control)
:final UpdateValueStrategy update = new UpdateValueStrategy(true, UpdateValueStrategy.POLICY_NEVER);
ctx.bindValue(SWTObservables.observeText(button), textObservable, null, update);
它导致SWTException:
无法创建视图:不支持窗口小部件[org.eclipse.swt.widgets.Button]。
有没有办法在SWT Button上进行文本绑定?
编辑
快速解决方案是将Label放在复选框旁边,然后可以使用
SWTObservables.observeText(label)
轻松完成绑定解
它适用于Eclipse 3.7
最佳答案
好。据我了解,用户选择一个按钮,选择被转移到模型,然后您希望按钮显示一些新文本。如果是这样,以下是解决方案:
DataBindingContext dbc = getBindingContext();
org.eclipse.swt.widgets.Button b = null; // New with the proper flag for CHECK
Object theModelBean = null; // Initialize as you wish
现在,您需要两个绑定。第一个绑定,将选择绑定到模型中的布尔值:
ISWTObservableValue targetBool = WidgetProperties.selection().observe(b);
IObservableValue modelBool = BeanProperties.value("someBooleanField").observe(theModelBean);
dbc.bindValue(targetBool, modelBool);
现在,当选择发生时,将在模型对象上调用“ setSomeBooleanField”方法。为了也更改按钮的文本,此设置器必须在模型对象上调用另一个设置器,以设置要显示的新“文本”。第二个设置器触发一个Property Change事件,该事件又唤醒您的第二个绑定,即:
IObservableValue targetText = BeanProperties.value("text").observe(b);
IObservableValue modelText = BeanProperties.value("theTextInTheBean").observe(theModelBean);
dbc.bindValue(targetText, modelText);
此绑定仅在模型到目标之间有效,因此您可以将targetToModel策略设置为NEVER。
您会看到,ViewerProperties不支持按钮的“文本”字段,但WidgetProperties和BeanProperties类都支持该按钮。只要setter触发属性更改事件,您就可以与BeanProperties绑定任何内容。
模型中的设置者必须是这样的:
public void setSomeBooleanField(boolean b){
firePropertyChange("someBooleanField", this.someBooleanField, this.someBooleanField = b);
// Form the new Text
this.setNewText(newText);
}
public void setNewText(String newText){
firePropertyChange("newText", this.newText, this.newText = newText); // Wake up the second Binding
}