问题描述
我可以将TextField
的text属性绑定到DoubleProperty
,如下所示:
I can bind a TextField
's text property to a DoubleProperty
, like this:
textField.textProperty().bindBidirectional(someDoubleProperty, new NumberStringConverter());
但是如果我的someDoubleProperty
是ReadOnlyDoubleProperty
的实例而不是DoubleProperty
怎么办?
But what if my someDoubleProperty
is an instance of ReadOnlyDoubleProperty
instead of DoubleProperty
?
我对双向绑定完全不感兴趣.我之所以使用这种方法,是因为没有这样的东西
I am acutally not interested in a bidirectional binding. I use this method only because there is no such thing as
textField.textProperty().bind(someDoubleProperty, new NumberStringConverter());
我是否需要使用侦听器,或者是否有绑定解决方案"?
Do I need to use listeners instead or is there a "binding-solution" for that as well?
有东西吗
textField.textProperty().bind(someDoubleProperty, new NumberStringConverter());
在那里?
推荐答案
对于单向绑定,您可以执行以下操作:
For a unidirectional binding, you can do:
textField.textProperty().bind(Bindings.createStringBinding(
() -> Double.toString(someDoubleProperty.get()),
someDoubleProperty));
第一个参数是生成所需字符串的函数.如果需要,您可以在此处使用自己选择的格式化程序.
The first argument is a function generating the string you want. You could use a formatter of your choosing there if you wanted.
第二个(和任何后续的)参数是要绑定的属性;也就是说,如果这些属性中的任何一个发生了更改,则绑定将无效(即需要重新计算).
The second (and any subsequent) argument(s) are properties to which to bind; i.e. if any of those properties change, the binding will be invalidated (i.e. needs to be recomputed).
等效地,您可以
textField.textProperty().bind(new StringBinding() {
{
bind(someDoubleProperty);
}
@Override
protected String computeValue() {
return Double.toString(someDoubleProperty.get());
}
});
这篇关于将TextField绑定到ReadOnlyDoubleProperty的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!