sialcasa / mvvmFX

an Application Framework for implementing the MVVM Pattern with JavaFX
Apache License 2.0
491 stars 105 forks source link

Disable input depend value property #532

Closed sidahmedbenkhaoua closed 6 years ago

sidahmedbenkhaoua commented 6 years ago

I want to do a mapping between disabled attribute of atextfield with attribute if it is not null

manuel-mauky commented 6 years ago

Hi, with MVVM style this would probably look like this:


public class MyView implements FxmlView<MyViewModel> {
    @FXML
    private TextField textField;

    @InjectViewModel
    private MyViewModel viewModel;

    public void initialize() {
        textField.textProperty().bindBidirectional(viewModel.valueProperty());
        textField.disableProperty().bind(viewModel.disabledProperty());
    }
}

public class MyViewModel implements ViewModel {
    private StringProperty value = new SimpleStringProperty();
    private BooleanProperty disabled = new SimpleStringProperty();

    public MyViewModel() {
        disabled.bind(value.isNotNull());
    }

    public StringProperty valueProperty() {
        return value;
    }
    public BooleanProperty disabledProperty() {
        return disabled;
    }

}

Without mvvm you could write it like this:

textField.disableProperty().bind(textField.textProperty().isNotNull());

However, with the mvvm version the View class has no clue about the rules when the textfield is disabled. If these rules change in the future (for example the text may not only not null but also not empty) you don't need to update the View code.