以下是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!
答案 0 :(得分:1)
此代码没有问题。 prop1
和prop2
是双向绑定的。当您查看您提供的输出时,显然就是这种情况。当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无关。