sialcasa / mvvmFX

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

How to get the index in an item of a list view #625

Open Jtpatato21 opened 2 years ago

Jtpatato21 commented 2 years ago

Currently I use the class CachedView Model Cell Factory.createForFxmlView(MyView.class) and I would like to know how I could get the getIndex method in my MyViewModel.class class since if I use ListCell returns a value of -1

I would like how this can be used in a listView.

Item View:

public class MyView implements FxmlView<MyViewModel> {

 @FXML
 private Label lblIndex;
 @InjectViewModel
 private MyViewModel viewModel;

 public void initialize() {
  lblIndex.textProperty().bind(viewModel.getIndexProperty());
 }

}

Item ViewModel:

public class MyViewModel implements ViewModel {

 private final IntegerProperty indexProperty = new SimpleIntegerProperty();

 public MyViewModel(int index){
  indexProperty.set(index);
 }

 public IntegerProperty getIndexProperty() {
  return indexProperty;
 }

}

Example using ListCell in ViewModel

public class MyViewModel extends ListCell<T> implements ViewModel {

 private final IntegerProperty indexProperty = new SimpleIntegerProperty();

 public MyViewModel(){
  indexProperty.set(this.getIndex()); // getIndex return -1 value;
 }

 public IntegerProperty getIndexProperty() {
  return indexProperty;
 }

}