【问题标题】:How to bind Node style (or styleClass) to a property?如何将 Node 样式(或 styleClass)绑定到属性?
【发布时间】:2018-01-10 00:30:26
【问题描述】:

考虑以下示例:

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 类绑定到属性?有没有不使用 CSS 的解决方案(意思是 style 块等)

【问题讨论】:

    标签: css kotlin tornadofx


    【解决方案1】:

    如果要切换类(基于布尔属性添加或删除类),可以使用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)
    }
    

    然后您可以将类设置为您想要的任何内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-23
      • 2018-06-09
      • 1970-01-01
      • 2014-03-01
      • 2020-02-11
      • 1970-01-01
      • 2021-04-20
      • 1970-01-01
      相关资源
      最近更新 更多