【问题标题】:ScalaFX. Label - How to bind IntegerProperty?斯卡拉FX。标签 - 如何绑定 IntegerProperty?
【发布时间】:2018-05-24 22:23:27
【问题描述】:

我有一个简单的表格,例如:

object Main extends JFXApp {
    stage = new PrimaryStage() {
        title = "My Form"
        scene = new Scene {
            root = new Label { text <== ViewModel.intProp }
        }
    }
}

还有一个简单的 ViewModel 示例:

object ViewModel {
  //Some mutable integer property. I want to keep it as IntegerProperty, not StringProperty
  val intProp = IntegerProperty(10)

  intProp.value = 15
}

如何将我的IntegerProperty 绑定到需要StringProperty 的标签?

【问题讨论】:

    标签: binding scalafx


    【解决方案1】:

    已编辑:我忘了.asString。呵呵!

    你可以简单的绑定属性如下:

    Main.scala:

    object Main extends JFXApp {
      stage = new PrimaryStage() {
        title = "My Form"
        scene = new Scene {
    
          // Bind label to int property as a string.
          root = new Label {
            text <== ViewModel.intProp.asString
          }
        }
      }
    }
    

    ViewModel.scala:

    object ViewModel {
      val intProp = IntegerProperty(10)
    
      intProp.value = 15
    }
    

    【讨论】:

    • 你帮了我大忙。这很不方便,什么 UI 绑定不执行隐式 toString 方法,例如,println 执行。
    • 是否可以在WPF 中使用Bind Converter 之类的东西?在我过去的C#develop. 中通过绑定转换器将一些数据绑定到 UI 对我有好处。
    • @Oleg 是的,可以使用NumberStringConverter,并设置双向绑定,但这不像这个例子那么简单,恕我直言。您可能想查看example JavaFX gist on GitHub。鉴于我们正在使用 ScalaFX,您会期望一个简单的 map 操作,但现在不存在。 :-(
    • 我的意思是 UI 的 Label.text 和 IntegerProperty 之间的转换器。 &lt;== 方法旁边的某个地方。其中 IntegerProperty 变成一个字符串,这个字符串发送到标签。没有 StringProperty。
    • 哇!多么简单。效果很好。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-27
    • 2011-09-16
    • 1970-01-01
    • 1970-01-01
    • 2016-01-31
    • 2017-10-23
    相关资源
    最近更新 更多