首页 > 解决方案 > 带有 selectionModelProperty 问题的 BooleanBinding

问题描述

我有一个带有文本字段、组合框和按钮的窗格。我希望该按钮仅在文本字段具有某些值并且组合选择了某些元素时启用,如果没有则禁用。默认情况下,组合没有选择。我试过这个:

button.disableProperty().bind(Bindings.createBooleanBinding(() ->
  (combo.getSelectionModel().getSelectedIndex() == -1) || 
    textfield.getText().trim().isEmpty(),
  textfield.textProperty(),
  combo.selectionModelProperty()
));

但不起作用。如果我删除 combo.selectionModelProperty() 按钮根据文本字段内容启用和禁用正确性,那么 combo.selectionModelProperty() 似乎没有检测到组合中的项目更改。有没有其他方法可以监听项目组合的变化?

标签: bindingjavafx-8

解决方案


可以替换a 本身的选择模型ComboBox,但这很不寻常,需要您自己进行替换。您正在尝试收听 的selectedIndex属性SelectionModel,因此您应该使用

combo.getSelectionModel().selectedIndexProperty()

或更好地使用该ComboBox.value属性:

button.disableProperty().bind(Bindings.createBooleanBinding(
    () -> (combo.getValue() == null) || textfield.getText().trim().isEmpty(),
    textfield.textProperty(),
    combo.valueProperty()
));

推荐阅读