代码之家  ›  专栏  ›  技术社区  ›  skiey

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

  •  2
  • skiey  · 技术社区  · 9 年前

    考虑以下示例:

    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 }
        }
    }
    

    如何动态更改的背景色 borderpane 取决于 someBooleanProperty (例如,当 true false )? 是否有可能将CSS类绑定到属性?有没有什么解决方案可以不使用CSS(意思是在 style

    1 回复  |  直到 5 年前
        1
  •  3
  •   Ruckus T-Boom    9 年前

    如果要切换类(基于布尔属性添加或删除类),可以使用 Node.toggleClass(CssRule, ObservableValue<Boolean>) 作用

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

    另一方面,如果希望绑定到不断变化的类值,则可以使用 Node.bindClass(ObservableValue<CssRule>) 作用

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