3

I have a simple form for example:

object Main extends JFXApp {
    stage = new PrimaryStage() {
        title = "My Form"
        scene = new Scene {
            root = new Label { text <== ViewModel.intProp }
        }
    }
}

And a simple example ViewModel:

object ViewModel {
  //Some mutable integer property. I want to keep it as IntegerProperty, not StringProperty
  val intProp = IntegerProperty(10)

  intProp.value = 15
}

How to bind my IntegerProperty to my Label, which expects StringProperty?

Jason Aller
  • 3,541
  • 28
  • 38
  • 38
Oleg
  • 899
  • 1
  • 8
  • 22

1 Answers1

4

Edited: I was forgetting about .asString. Doh!

You can simply bind the property as follows:

Main.scala:

object Main extends JFXApp {
  stage = new PrimaryStage() {
    title = "My Form"
    scene = new Scene {

      // Bind label to int property as a string.
      root = new Label {
        text <== ViewModel.intProp.asString
      }
    }
  }
}

ViewModel.scala:

object ViewModel {
  val intProp = IntegerProperty(10)

  intProp.value = 15
}
Mike Allen
  • 8,139
  • 2
  • 24
  • 46
  • You helped me agian. It's unconvenient, what UI bindings doesn't perform implicit `toString` method, like, for example, `println` does. – Oleg Dec 13 '17 at 09:11
  • Is it possible to use something like `Bind Converter` in `WPF`? It was good for me to bind some data to UI via bind converter in my past `C#` develop. – Oleg Dec 13 '17 at 09:19
  • @Oleg Yes, it's possible to use a `NumberStringConverter`, and setup a bi-directional binding, but that's not as straighforward as this example, IMHO. There's an [example _JavaFX_ gist on _GitHub_](https://gist.github.com/jundl77/c4b2be5286c58d4f102b) that you might want to look at. Given that we're using _ScalaFX_, you would expect a simple `map` operation, but that doesn't exist right now. :-( – Mike Allen Dec 13 '17 at 11:45
  • I mean converter between UI's Label.text and IntegerProperty. Somewhere beside `<==` method. Where IntegerProperty becomes a string and this string sends to the label. Without StringProperty. – Oleg Dec 13 '17 at 12:34
  • @Oleg I updated the answer to use `.asString`. It's not represented explicitly in the _ScalaFX API_, so I forgot about it. Let me know how that works out for you... – Mike Allen Dec 13 '17 at 14:23
  • 1
    Wow! How simply. Works great. Thank you very much! – Oleg Dec 13 '17 at 14:34