tornadofx icon indicating copy to clipboard operation
tornadofx copied to clipboard

Unbind TextField text property from non-String property

Open codezan opened this issue 3 years ago • 2 comments

Using this guide: https://docs.tornadofx.io/0_subsection/11_editing_models_and_validation

I created a custom View that displays a "FolderModel" class, which holds a nameProperty and a pathProperty. In the example

private fun editPerson(person: Person?) {
        if (person != null) {
            prevSelection?.apply {
                nameProperty.unbindBidirectional(nameField.textProperty())
                titleProperty.unbindBidirectional(titleField.textProperty())
            }
            nameField.bind(person.nameProperty)
            titleField.bind(person.titleProperty)
            prevSelection = person
        }
    }

binds both String properties to the appropriate fields and unbinds the previous selection as needed.

When trying to recreate this, I run into the problem of unbinding the previous model from the textfield bound to it:

    if(currentFolder != null) {
      currentFolder?.apply {
        nameProperty.unbindBidirectional(nameField.textProperty())
        pathProperty.unbindBidirectional(pathField.textProperty()) // <-- this won't compile because pathProperty is an ObjectProperty<Path>!
      }
    }

    nameField.bind(folder.nameProperty)
    pathField.bind(folder.pathProperty, converter = object: StringConverter<Path>() {
      override fun toString(path: Path?): String = path?.toString() ?: ""
      override fun fromString(string: String?): Path? = string?.let { try { Path.of(string) } catch (e: Exception) { null } }
    })
    currentFolder = folder

What's the proper way to unbind an ObjectProperty from a TextField after it's bound using a StringConverter?

codezan avatar Nov 04 '21 14:11 codezan

Try use javafx.beans.binding.Bindings.unbindBidirectional(Object property1, Object property2)

yamert89 avatar Nov 05 '21 11:11 yamert89

The proper way to approach this is to create a FolderViewModal that extends ItemViewModal and inject that into your FolderView and bind it there. Then you can set the item of the FolderViewModal as needed.

SKeeneCode avatar Nov 05 '21 15:11 SKeeneCode