Skip to content

Data binding

A document shows view model fields and reacts to their changes. Use it to keep what the player sees in step with game data without writing update code. The page uses seven samples (see Samples): FieldBinding, Lists, StructList, NestedViewModel, Aliases, InnerRml and VirtualList.

Fields

A document reads only Field Notify fields: a Blueprint visible property marked FieldNotify, or a const BlueprintCallable function that has only a return value. The document updates when the model broadcasts the field. In a Blueprint view model, turn Field Notify on in the variable's Details (Blueprint view models). In C++, UE_MVVM_SET_PROPERTY_VALUE writes a field and broadcasts it; a plain assignment is not seen. A document never writes a field; it calls a function that does (Events).

A field binds under its exact property name: a C++ bool bVisible is <model>.bVisible in the document, not <model>.Visible, because the b prefix stays. An enum field reads as its short name, so write Mode == 'Combat', not ECombatMode::Combat; a Blueprint enum reads as the name you typed for the entry. A Blueprint variable with a space, such as Max Health, is Max_Health in the document. If two fields would get the same name, the first keeps it and the validator warns about the other. A Blueprint function with a space in its name cannot be called from a document.

The FieldBinding sample has one field of each simple type:

FieldBinding/ArcRmlSamplesFieldBinding.h
UPROPERTY(BlueprintReadOnly, FieldNotify, Category = "Samples")
int32 Count = 0;

UPROPERTY(BlueprintReadOnly, FieldNotify, Category = "Samples")
float Progress = 0.0f;

UPROPERTY(BlueprintReadOnly, FieldNotify, Category = "Samples")
bool bEven = true;

UPROPERTY(BlueprintReadOnly, FieldNotify, Category = "Samples")
FText Message = INVTEXT("Not clicked yet");

UPROPERTY(BlueprintReadOnly, FieldNotify, Category = "Samples")
FLinearColor Accent = FLinearColor(0.2f, 0.6f, 1.0f);

UFUNCTION(BlueprintCallable, Category = "Samples")
void Increment();
FieldBinding/ArcRmlSamplesFieldBinding.cpp
void UArcRmlSamplesFieldBindingViewModel::Increment()
{
    const FLinearColor Accents[] = {FLinearColor(0.2f, 0.6f, 1.0f), FLinearColor(1.0f, 0.55f, 0.1f), FLinearColor(0.3f, 0.85f, 0.4f)};

    const int32 NewCount = Count + 1;
    UE_MVVM_SET_PROPERTY_VALUE(Count, NewCount);
    UE_MVVM_SET_PROPERTY_VALUE(Progress, (NewCount % 11) / 10.0f);
    UE_MVVM_SET_PROPERTY_VALUE(bEven, NewCount % 2 == 0);
    UE_MVVM_SET_PROPERTY_VALUE(Message, FText::Format(INVTEXT("Clicked {0} times"), NewCount));
    UE_MVVM_SET_PROPERTY_VALUE(Accent, Accents[NewCount % UE_ARRAY_COUNT(Accents)]);
}

{{ Field }} prints a field. These attributes bind a field of the document's view model, or an expression, to an element. The FieldBinding sample declares its model fields in the head and puts :model="fields" on <body>, so every binding below reads it (Documents). It uses :if, class:*, style:*, attr:* and on:click; lists are in the Lists sample below.

Attribute Effect
:if="expr" The element is shown only while the expression is true. A :if, :for or :visible whose expression fails (syntax error, unknown name) hides its element, and a failed {{ }} prints nothing; the log names the cause (Expressions).
:visible="expr" Sets visibility; the element keeps its layout.
class:<name>="expr" Adds the class <name> while the expression is true.
style:<property>="expr" Sets one style property from the expression.
attr:<name>="expr" Sets an attribute from the expression.
attrif:<name>="expr" Sets the attribute <name> to empty while the expression is true and removes it while it is false. The tab bar marks its current tab this way.
:for, :key Repeat an element per row, see Lists.
on:<event>="..." Run an expression on an event, see Events.
FieldBinding.rml
<p>Count: {{ fields.Count }}</p>
<p>Progress: {{ fields.Progress | format(1) }}</p>
<p>{{ fields.Message | to_upper }}</p>
<p :if="fields.bEven">The count is even.</p>
<p :if="!fields.bEven">The count is odd.</p>
<div class="fb-badge" class:fb-odd="!fields.bEven">odd or even</div>
<div class="fb-bar"><div class="fb-fill" style:width="(fields.Progress * 100) + '%'" style:background-color="fields.Accent"></div></div>
<progress class="fb-progress" max="1" attr:value="fields.Progress"></progress>

The FieldBinding sample: count, progress, upper-cased message, the even line, the odd-or-even badge, a bar and Add one and Close buttons

Expressions can read fields (bEven, Progress), combine with operators, and call transforms with |. Text is single-quoted. The whole language, every transform and what an error does: Expression reference.

Other models

<model>.<Field> reads a field of another view model by its name, for example {{ ui.Theme }}: any model the document or its frame declares. It works in expressions, attributes and :for, and writes the model it names (Forms). The element's own model is read with its name in front too (<own model>.Theme); a read without a model name resolves empty and logs an error. A :for row or alias: of an outer element stays readable inside a nested :model element, and a write through it goes to the outer model.

The first name is looked up in this order: the element's own model name, a alias:* or :for name, then the name of another model; ev and ArcKeys are built in. A loop name hides a model of the same name. Until that model exists, the read gives an empty value and logs Could not get value from data variable; the view updates when the model is created.

Transforms

value | name(arguments) changes a value on its way into the document. In the sample, Progress | format(1) prints one decimal and Message | to_upper upper-cases the text.

Every transform, with its arguments and what a wrong argument does, is in the Expression reference.

Types

Field type In the document
bool Boolean.
Integer types Integer.
float, double Number.
Enum Its name as text.
FString, FName, FText Text.
FGameplayTag Its name as text.
FGameplayTagContainer An array of names.
FLinearColor, FColor Colour; style:background-color="Accent" in the sample.
FSoftObjectPath, soft pointers, UTexture* Text asset:<path>.
FArcRmlImageRef Its Path as text.
A view model object A nested model, see Nested view models.
TArray An array.
Any other struct A struct with all its members, read by member name (row.Name). A Blueprint struct member is read by the name typed in the editor.
FArcRmlStructList An array of its rows, see Struct lists.
TMap, TSet, other objects Empty; a warning is logged once per field.

Nesting is read up to 16 levels deep.

Lists

A TArray is a list. :model="lists" on an element makes the fields of the view model declared under that name readable inside it as lists.Items, that view model's array. :for="row, index : lists.Items" makes one element per row; row and index are names the author chooses (without them the row is it and the index it_index). :key="row.Name" on the same element keeps a row's element across inserts and removals, matched by that value. The Lists sample:

Lists.rml
<div class="ls-row" :for="row, index : lists.Items" :key="row.Name">
    <span class="ls-name">{{ index + 1 }}. {{ row.Name }}</span>
    <span>x{{ row.Quantity }}</span>
    <button class="ls-remove ls-button" on:click="call('lists', 'Remove', index)">Remove</button>
</div>
Lists/ArcRmlSamplesLists.h
USTRUCT(BlueprintType)
struct FArcRmlSamplesListsRow
{
    GENERATED_BODY()

    UPROPERTY(BlueprintReadOnly, Category = "Samples")
    FString Name;

    UPROPERTY(BlueprintReadOnly, Category = "Samples")
    int32 Quantity = 0;
};

UCLASS()
class UArcRmlSamplesListsViewModel : public UMVVMViewModelBase
{
    GENERATED_BODY()

public:
    UArcRmlSamplesListsViewModel();

    UPROPERTY(BlueprintReadOnly, FieldNotify, Category = "Samples")
    TArray<FArcRmlSamplesListsRow> Items;

    UFUNCTION(BlueprintCallable, Category = "Samples")
    void Add();

    UFUNCTION(BlueprintCallable, Category = "Samples")
    void Remove(int32 Index);

private:
    int32 NextNumber = 1;
};

A plain array sends its whole value when it changes, so announce the change with UE_MVVM_BROADCAST_FIELD_VALUE_CHANGED(Items) after you edit it:

Lists/ArcRmlSamplesLists.cpp
void UArcRmlSamplesListsViewModel::Add()
{
    FArcRmlSamplesListsRow Row;
    Row.Name = FString::Printf(TEXT("Item %d"), NextNumber);
    Row.Quantity = NextNumber;
    ++NextNumber;
    Items.Add(Row);
    UE_MVVM_BROADCAST_FIELD_VALUE_CHANGED(Items);
}

void UArcRmlSamplesListsViewModel::Remove(int32 Index)
{
    if (Items.IsValidIndex(Index))
    {
        Items.RemoveAt(Index);
        UE_MVVM_BROADCAST_FIELD_VALUE_CHANGED(Items);
    }
}

call('lists', 'Remove', index) passes the index as an argument; the function checks it before it uses it.

The Lists sample: three rows "Item 1" to "Item 3" with quantities and a Remove button each, then Add and Close

Struct lists

A plain array sends everything on every change. For a long list that changes often, hold the rows in an FArcRmlStructList: it sends only the rows that were inserted, removed, moved or changed. Blueprint view models cannot use it. The StructList sample holds the same rows as Lists:

StructList/ArcRmlSamplesStructList.h
USTRUCT(BlueprintType)
struct FArcRmlSamplesStructListRow
{
    GENERATED_BODY()

    UPROPERTY(BlueprintReadOnly, Category = "Samples")
    FString Id;

    UPROPERTY(BlueprintReadOnly, Category = "Samples")
    FString Name;

    UPROPERTY(BlueprintReadOnly, Category = "Samples")
    int32 Quantity = 0;
};
StructList/ArcRmlSamplesStructList.cpp
UArcRmlSamplesStructListViewModel::UArcRmlSamplesStructListViewModel()
{
    Rows.SetRowType(FArcRmlSamplesStructListRow::StaticStruct());
    for (int32 Index = 0; Index < 3; ++Index)
    {
        AddRow();
    }
}

void UArcRmlSamplesStructListViewModel::AddRow()
{
    FArcRmlSamplesStructListRow Row;
    Row.Id = FString::Printf(TEXT("row-%d"), NextNumber);
    Row.Name = FString::Printf(TEXT("Item %d"), NextNumber);
    Row.Quantity = NextNumber;
    ++NextNumber;
    Rows.Set(Row.Id, Row);
}

void UArcRmlSamplesStructListViewModel::Bump(int32 Index)
{
    if (!Rows.GetKeys().IsValidIndex(Index))
    {
        return;
    }
    const FString Key = Rows.GetKeys()[Index];
    const FArcRmlSamplesStructListRow* Current = Rows.FindAs<FArcRmlSamplesStructListRow>(Key);
    if (Current)
    {
        FArcRmlSamplesStructListRow Row = *Current;
        ++Row.Quantity;
        Rows.Set(Key, Row);
        UE_MVVM_BROADCAST_FIELD_VALUE_CHANGED(Rows);
    }
}

void UArcRmlSamplesStructListViewModel::Reverse()
{
    TArray<FString> Order = Rows.GetKeys();
    Algo::Reverse(Order);
    Rows.SetOrder(Order);
    UE_MVVM_BROADCAST_FIELD_VALUE_CHANGED(Rows);
}
  • SetRowType names the row struct, and the constructor calls it before any row is set.
  • Set(Key, Row) adds the row or replaces the row with that key, Remove(Key) deletes it and SetOrder(Keys) sets the order; GetKeys() lists the keys in order and FindAs<Row>(Key) reads a row.
  • After a change the field is announced with UE_MVVM_BROADCAST_FIELD_VALUE_CHANGED(Rows).

The document reads the rows like an array. The key given to Set and the Id member are the same text here, so :key="row.Id" matches:

StructList.rml
<div class="sl-row" :for="row, index : rows.Rows" :key="row.Id">
    <span class="sl-name">{{ row.Name }}</span>
    <span>x{{ row.Quantity }}</span>
    <button class="sl-bump sl-button" on:click="call('rows', 'Bump', index)">+1</button>
    <button class="sl-remove sl-button" on:click="call('rows', 'Remove', index)">Remove</button>
</div>

Nested view models

A field that holds a view model object, or an array of them, can be read through the parent's field name and called. Use it when each part is an object the game updates on its own and the document calls: a party with a leader and members, each its own view model. A struct array (above) holds plain data rows; a child announces its own changes and can be called. The NestedViewModel sample is that party: the leader is Child, the members are Children.

NestedViewModel/ArcRmlSamplesNestedViewModel.h
UCLASS()
class UArcRmlSamplesNestedParentViewModel : public UMVVMViewModelBase
{
    GENERATED_BODY()

public:
    UArcRmlSamplesNestedParentViewModel();

    UPROPERTY(BlueprintReadOnly, FieldNotify, Category = "Samples")
    TObjectPtr<UArcRmlSamplesNestedChildViewModel> Child;

    UPROPERTY(BlueprintReadOnly, FieldNotify, Category = "Samples")
    TArray<TObjectPtr<UArcRmlSamplesNestedChildViewModel>> Children;
};
NestedViewModel/ArcRmlSamplesNestedViewModel.cpp
UArcRmlSamplesNestedParentViewModel::UArcRmlSamplesNestedParentViewModel()
{
    Child = CreateDefaultSubobject<UArcRmlSamplesNestedChildViewModel>(TEXT("Child"));
    Child->Name = TEXT("Leader");

    const TCHAR* ChildNames[] = {TEXT("Archer"), TEXT("Healer"), TEXT("Scout")};
    for (const TCHAR* ChildName : ChildNames)
    {
        UArcRmlSamplesNestedChildViewModel* Member = CreateDefaultSubobject<UArcRmlSamplesNestedChildViewModel>(ChildName);
        Member->Name = ChildName;
        Children.Add(Member);
    }
}

The children are subobjects of the parent, made with CreateDefaultSubobject, so the create source makes the parent and its children together.

NestedViewModel.rml
<span class="nv-heading">Leader</span>
<div class="nv-row">
    <span class="nv-name">{{ party.Child.Name }}</span>
    <span id="nv-child-points">{{ party.Child.Points }} points</span>
</div>
<span class="nv-heading">Members</span>
<div class="nv-row" :for="member : party.Children">
    <span class="nv-name">{{ member.Name }}</span>
    <span>{{ member.Points }} points</span>
</div>

{{ Child.Name }} reads a field of the leader, and member in :for="member : Children" is one member. A leader or member announces its own changes and the document updates the value read through the parent. A call names the model it targets, see Events.

Aliases

alias:<name>="Path" makes <name> stand for the field path Path on that element and everything inside it. Use it to shorten a long path you read many times. The Aliases sample shows the selected hero through sel:

Aliases.rml
<div class="al-card" alias:sel="al.Selected">
    <p id="al-name" class="al-name">{{ sel.Name }}</p>
    <p>{{ sel.Title }}, level {{ sel.Level }}</p>
</div>
<p id="al-long" class="al-result">Same name, written in full: {{ al.Selected.Name }}</p>
  • {{ sel.Name }} reads Selected.Name, so the two lines show the same text. When the "Next hero" button changes Selected, both lines update.
  • A model field with the same name as the alias wins over it, and the log warns that the alias is shadowed. Pick a name no field has.
  • In a component, the alias path must come from a prop whose value is a whole {{ path }}.

Inner RML

{{ }} shows a string as text. :rml="Banner" shows it as markup: it replaces the element's children with the string parsed as RML, again each time the string changes. The InnerRml sample shows one string from the game and one the player types:

InnerRml.rml
<p id="ir-banner" class="ir-line" :rml="ir.Banner"></p>
<!-- ... -->
<p id="ir-text" class="ir-line">{{ ir.Typed }}</p>
<!-- ... -->
<p id="ir-rml" class="ir-line" :rml="ir.Typed"></p>

Banner is Welcome back, <span class="ir-gold">traveller</span>: the <span> becomes an element that the style sheet colours. Typed starts as <b>x</b>: {{ Typed }} shows those characters as they are, :rml turns them into a <b> element holding x.

Never put player text in :rml

Nothing is escaped in :rml. A name, a chat line or a note a player typed can hold markup, and it becomes elements: a player can insert an <img> or a styled <span>. Show player text with {{ }} and use :rml only for strings your own game or data wrote.

A localised text (loc) in :rml is a compile error.

Virtual lists

A list of thousands of rows needs only the rows near the visible part. :virtual on a :for element creates the elements for a window of entries and leaves the rest as data. The VirtualList sample shows 10 000 numbers:

VirtualList.rml
<div id="vl-list" class="vl-list">
    <button class="vl-row" :for="number : vl.Rows" :virtual>Row {{ number }}</button>
</div>
VirtualList.rcss
.vl-list {
    height: 360px;
    overflow-y: auto;
    background-color: #1b212b;
    border-radius: 4px;
}

.vl-row {
    display: block;
    width: 100%;
    height: 36px;
    padding: 0 16px;
    text-align: left;
    background-color: #303846;
    border-bottom: 1px #1b212b;
}

Rows is a TArray<int32> that the view model fills with 1 to 10 000; {{ Rows.size }} is the entry count.

The VirtualList sample: a scrolling box of buttons Row 1 to Row 10 under the line "10000 rows, only the ones near the visible part exist"

  • The parent of the :for element is the scroll container. It needs a fixed height and overflow-y: auto or scroll. A parent that does not scroll vertically creates no rows, and the log shows the error Virtual :for on <address>: its parent must scroll vertically.
  • Every row takes the size of the first row (its margin box). Rows of different heights, horizontal lists and other children in the scroll container are not supported.
  • The elements that exist are the visible rows plus one box height before and after. The scroll bar keeps the length of the whole list.
  • A row that leaves the window is removed, and with it its focus, hover and animations. When the rows are buttons, Up and Down move focus row by row and the box scrolls to keep the focused row in view.
  • :key works as in Lists, but a key is read only for the rows in the window, so a repeated key outside it is not detected.
  • Two spacer elements before and after the rows give the scroll bar its length. They count as siblings, so :first-child, :nth-child, + and ~ on a row count them too. Style rows by class.
  • On a dc-import, put :virtual on the host wrapper with :for (Components).