双向绑定无法绑定

时间:2015-09-19 06:22:40

标签: scala data-binding javafx scalafx

以下是Pro ScalaFX的示例:

package proscalafx.ch03

import scalafx.beans.property.StringProperty

object BidirectionalBindingExample extends App {
  println("Constructing two StringProperty objects.")
  val prop1 = new StringProperty("")
  val prop2 = new StringProperty("")

  println("Calling bindBidirectional (<==>).")
  prop2 <==> prop1

  println("prop1.isBound = " + prop1.isBound)
  println("prop2.isBound = " + prop2.isBound)

  println("Calling prop1.set(\"prop1 says: Hi!\")")
  prop1() = "prop1 says: Hi!"
  println("prop2.get returned:")
  println(prop2())

  println( """Calling prop2.set(prop2.get + "\nprop2 says: Bye!")""")
  prop2() = prop2() + "\nprop2 says: Bye!"
  println("prop1.get returned:")
  println(prop1())
}

两个StringProperty对象应该相互绑定,当其中一个更新时,另一个也应该更新。这不是真的:

Constructing two StringProperty objects.
Calling bindBidirectional (<==>).
prop1.isBound = false
prop2.isBound = false
Calling prop1.set("prop1 says: Hi!")
prop2.get returned:
prop1 says: Hi!
Calling prop2.set(prop2.get + "\nprop2 says: Bye!")
prop1.get returned:
prop1 says: Hi!
prop2 says: Bye!

1 个答案:

答案 0 :(得分:1)

此代码没有问题。 prop1prop2是双向绑定的。当您查看您提供的输出时,显然就是这种情况。当prop1的值设置为“prop1说:嗨!”时prop2的值也会更改,当您更改prop2时,prop1正在发生变化。请仔细查看输出。

可能令人困惑的一件事是isBound为两个属性返回false。这是双向绑定的正确行为。仅当属性与另一个属性单向绑定时,isBound才会返回true。因此,如果您将代码更改为:

prop2 <== prop1
println("prop1.isBound = " + prop1.isBound)
println("prop2.isBound = " + prop2.isBound)

你会得到

prop1.isBound = false
prop2.isBound = true

这就是JavaFX的工作原理,与ScalaFX无关。