如何将 Node 样式(或 styleClass)绑定到 属性?

How to bind Node style (or styleClass) to a property?

考虑以下示例:

class MainView : View("Example") {
    val someBooleanProperty: SimpleBooleanProperty = SimpleBooleanProperty(true)
    override val root = borderpane {
        paddingAll = 20.0
        center = button("Change bg color") {
            action {
                // let's assume that new someBooleanProperty value is updated
                // from some API after button clicked
                // so changing style of the borderpane in action block
                // of the button is not the solution
                someBooleanProperty.value = !someBooleanProperty.value
            }
        }
    }
}

class Styles : Stylesheet() {
    companion object {
        val red by cssclass()
        val green by cssclass()
    }

    init {
        red { backgroundColor += Color.RED }
        green { backgroundColor += Color.GREEN }
    }
}

如何根据 someBooleanProperty 动态更改 borderpane 的背景颜色(例如 true 时为红色,false 时为绿色)?是否可以将 CSS class 绑定到 属性?有没有不使用 CSS 的解决方案(意思是在 style 块内等)

如果您想切换 class(根据布尔值 属性 添加或删除 class),您可以使用 Node.toggleClass(CssRule, ObservableValue<Boolean>) 函数。

val someBooleanProperty = SimpleBooleanProperty(true)
...
borderpane {
    toggleClass(Styles.red, someBooleanProperty)
    toggleClass(Styles.green, someBooleanProperty.not())
}

另一方面,如果您想绑定到一个变化的 class 值,您可以使用 Node.bindClass(ObservableValue<CssRule>) 函数。

val someClassyProperty = SimpleObjectProperty(Styles.red)
...
borderpane {
    bindClass(someClassyProperty)
}

然后您可以将 class 设置为您想要的任何值。