fx:context directive

The default evaluation context is the root element of the FXML document. This can be changed with the fx:context directive, which can be set to an arbitrary object. Paths in an expression will then be resolved against the object referenced by fx:context.

fx:context can only be set on the root node of the FXML document.

Static object in element notation

The value of fx:context can be a static object that is instantiated in the FXML document with element notation. The object exists outside of the scene graph and is internally stored by the root node.

<StackPane xmlns="http://javafx.com/javafx" xmlns:fx="http://jfxcore.org/fxml/2.0">
    <fx:context>
        <!-- Instantiate MyBindingContext and set it as the control's context -->
        <MyBindingContext/>
    </fx:context>

    <!-- "user.name" will be evaluated against MyBindingContext -->
    <Label text="${user.name}"/>
</StackPane>
class MyBindingContext {
    ObjectProperty<User> userProperty();
    ...
}

class User {
    StringProperty nameProperty();
    ...
}

Path to an object

The evaluation context may also be exposed with a field, getter, or ObservableValue on the code-behind class. In this case, the value of fx:context is a path.

com/sample/MyControl.fxml
<StackPane xmlns="http://javafx.com/javafx" xmlns:fx="http://jfxcore.org/fxml/2.0"
           fx:subclass="com.sample.MyControl"
           fx:context="$myContext">
    <!-- "user.name" will be resolved against "myContext" -->
    <Label text="${user.name}"/>
</StackPane>
com/sample/MyControl.java
public class MyControl extends MyControlBase {
    final MyBindingContext myContext;

    MyControl() {
        myContext = new MyBindingContext();
        initializeComponent();
    }
}

class MyBindingContext {
    ObjectProperty<User> userProperty();
    ...
}

The fx:context directive supports unidirectional bindings, which is useful when the evaluation context object can change and is exposed as an ObservableValue. Note that this will incur listener management overhead. If possible, a one-time assignment should be preferred.


This site uses Just the Docs, a documentation theme for Jekyll.