在 JavaFX 中使用转换进行单向绑定和设置

unidirectional bind and set with conversion in JavaFX

我最近在我的 JavaFX 应用程序中编写了这样的函数:

public static <T1, T2> void bindAndSet(ReadOnlyProperty<T1> sourceProperty, Property<T2> targetProperty, Function<T1, T2> converter) {
    sourceProperty.addListener(new WeakChangeListener<>((obs, oldVal, newVal) -> targetProperty.setValue(converter.apply(newVal))));
    targetProperty.setValue(converter.apply(sourceProperty.getValue()));
}

这是一个带有转换和设置初始值的单向绑定。 我在 JavaFX 方面的经验很少,但它似乎应该是使用绑定的应用程序中非常常见的部分。 Property#bind 似乎几乎没用。它不允许转换类型,并且从检查源代码来看它没有设置初始值。

是否有一种(或两种)方法可以提供这种功能? 或者我使用 JavaFX API 的方式有误?

您可以使用 Bindings.createObjectBinding():

targetProperty.bind(Bindings.createObjectBinding(
        () -> converter.apply(sourceProperty.get()), sourceProperty));