首页 > 解决方案 > Bind ItemViewModel to domain class list

问题描述

I have a Rulebook that contains Rules:

class Rulebook(val rules:MutableList<Rule>)

I have an ItemViewModel for it, as it's used in a multiply-nested selection UI.

class RulebookModel : ItemViewModel<Rulebook> {
    val rulesProperty = bind // ... here's my problem
}

What is the correct binding to be able to initialize a tableview with the property?

A naive bind yields the wrong type:

val rulesProperty = bind(Rulebook::rules)

has type Property<MutableList<Rule>>, which tableview() doesn't take.

From another answer here I got Link

val rulesProperty = bind(Rulebook::rules) as ListProperty<Rule>

This yields the correct type, so we get through compilation, but at runtime I get this:

java.lang.ClassCastException: java.util.ArrayList cannot be cast to javafx.collections.ObservableList

Note: The RulebookModel does start life without an item in it yet. I've seen ArrayLists come from empty list factory calls before. Is that possibly my actual problem?

What is the correct way to perform this binding?

标签: tornadofx

解决方案


您的模型需要有一个 SimpleListProperty 才能绑定到 itemViewModel 下面是一些关于如何编写类和表视图的示例代码:

data class rule(val name: String, val def: String)
class RuleBookModel{
  val rulesProperty = SimpleListProperty<rule>()
  var rules by rulesProperty
}
class RuleBookViewModel: ItemViewModel<RuleBookModel>() {
  val rules = bind(ruleBook::rulesProperty)
}

class TestView : View("Test View") {
  val myRuleBook: RuleBookViewModel by inject()
  init {
      // adding a rule so the table doesn't look lonely
      myRuleBook.rules.value.add(rule("test", "fuga"))
  }
  val name = textfield()
  val definition = textfield()
  override val root = vbox{
    hbox {
       label("Name")
       add(name)
    }
    hbox {
       label("Definition")
       add(definition)
    }
    button("Add a rule").action{
        myRuleBook.rules.value.add(rule(name.text, definition.text))
    }
    tableview(myRuleBook.rules) {
        column("name", rule::name)
        column("def", rule::def)
    }
  }
}

推荐阅读