考虑以下示例:
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 类绑定(bind)到属性?有没有任何解决方案可以在不使用 CSS 的情况下做到这一点(意思是在 style
block 等内部)
最佳答案
如果要切换类(根据 bool 属性添加或删除类),可以使用 Node.toggleClass(CssRule, ObservableValue<Boolean>)
功能。
val someBooleanProperty = SimpleBooleanProperty(true)
...
borderpane {
toggleClass(Styles.red, someBooleanProperty)
toggleClass(Styles.green, someBooleanProperty.not())
}
另一方面,如果您想绑定(bind)到更改的类值,则可以使用 Node.bindClass(ObservableValue<CssRule>)
功能。
val someClassyProperty = SimpleObjectProperty(Styles.red)
...
borderpane {
bindClass(someClassyProperty)
}
然后您可以将类设置为您想要的任何内容。
关于css - 如何将节点样式(或 styleClass)绑定(bind)到属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45466631/