09.04.2018 Views

tornadofx-guide

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Advanced Data Controls<br />

Assign If Null<br />

If you have a reason for wanting to recreate the graphic property for a list cell, you can use<br />

the assignIfNull helper, which will assign a value to any given property if the property<br />

doesn't already contain a value. This will make sure that you avoid creating new nodes if<br />

updateItem is called on a cell that already has a graphic property assigned.<br />

cellFormat {<br />

graphicProperty().assignIfNull {<br />

label("Hello")<br />

}<br />

}<br />

ListCellFragment<br />

The ListCellFragment is a special fragment which can help you manage ListView cells. It<br />

extends Fragment , and includes some extra ListView specific fields and helpers. You<br />

never instantiate these fragments manually, instead you instruct the ListView to create<br />

them as needed. There is a one-to-one correlation between ListCell and<br />

ListCellFragment instances. Only one ListCellFragment instance will over its lifecycle be<br />

used to represent different items.<br />

To understand how this works, let's consider a manually implemented ListCell , essentially<br />

the way you would do in vanilla JavaFX. The updateItem function will be called when the<br />

ListCell should represent a new item, no item, or just an update to the same item. When<br />

you use a ListCellFragment , you do not need to implement something akin to updateItem ,<br />

but the itemProperty inside it will update to represent the new item automatically. You can<br />

listen to changes to the itemProperty , or better yet, bind it directly to a ViewModel . That<br />

way your UI can bind directly to the ViewModel and no longer need to care about changes to<br />

the underlying item.<br />

Let's recreate the form from the cellFormat example using a ListCellFragment . We need a<br />

ViewModel which we will call PersonModel (Please see the Editing Models and Validation<br />

chapter for a full explanation of the ViewModel ) For now, just imagine that the ViewModel<br />

acts as a proxy for an underlying Person , and that the Person can be changed while the<br />

observable values in the ViewModel remain the same. When we have created our<br />

PersonCellFragment , we need to configure the ListView to use it:<br />

listview(personlist) {<br />

}<br />

cellFragment(PersonCellFragment::class)<br />

203

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!