> For the complete documentation index, see [llms.txt](https://docs.flatredball.com/gum/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.flatredball.com/gum/code/styling/runtime-variable-references.md).

# Runtime Variable References

## Introduction

Variable references defined in the Gum tool can be re-evaluated at runtime, allowing you to change style values in code and propagate them across your entire project before creating UI. This is useful for theming, accessibility settings, or any scenario where centralized style values need to change at startup or during gameplay.

{% hint style="info" %}
Runtime variable references require Gum NuGet packages version 2026.4 or newer. The optional `Gum.Expressions` NuGet is also available starting from this version.
{% endhint %}

For information on setting up variable references in the Gum tool, see the [Variable References](https://docs.flatredball.com/gum/gum-tool/gum-elements/general-properties/variable-references.md) page. For a semantic color palette (`Primary`, `Success`, `Danger`, and so on) that every instance in your project can share and that this API can recolor at runtime, see [Semantic Color Categories on Standard Elements](https://docs.flatredball.com/gum/gum-tool/gum-elements/general-properties/variable-references.md#example-semantic-color-categories-on-standard-elements).

## Propagating Variable References

`ApplyAllVariableReferences` operates at the project level, modifying values on `ElementSave` and `StateSave` objects rather than on live `GraphicalUiElement` visuals. When you change style values in code, call it before creating your UI, and any controls created afterward use the updated values. A project loaded through `Initialize` already applies its references before the first control is created, so style files edited outside the Gum tool show the same values as a [hot reload](https://docs.flatredball.com/gum/code/debugging/hot-reload.md) of that edit without any call. To update visuals which are already on screen, see [Live Updates Within a Component](#live-updates-within-a-component) and [Refreshing Live Visuals After Style Changes](#refreshing-live-visuals-after-style-changes).

{% hint style="info" %}
Available in November 2026, or now if building Gum from source.
{% endhint %}

After [loading a Gum project](https://docs.flatredball.com/gum/code/getting-started/setup/loading-a-gum-project-.gumx.md), you can modify style variables and call `ApplyAllVariableReferences` to propagate changes across all elements in dependency order. Elements that are referenced by others are applied first, so downstream references always pick up the latest values.

```csharp
// Initialize
var project = ObjectFinder.Self.GumProjectSave;

// Find your style component and change values
var styles = project.Components.First(item => item.Name == "Styles");

styles.DefaultState.SetValue("Primary.Red", 255);
styles.DefaultState.SetValue("Primary.Green", 0);
styles.DefaultState.SetValue("Primary.Blue", 0);

// Propagate all variable references across the project
ObjectFinder.Self.GumProjectSave.ApplyAllVariableReferences();

// Now create UI - it will use the updated values
project.Screens.First().ToGraphicalUiElement().AddToRoot();
```

The `ApplyAllVariableReferences` method iterates all elements (standards, components, and screens) and applies variable references on every state, including category states. It automatically handles dependency ordering so that if element B references element A, element A's references are applied first.

## Live Updates Within a Component

A variable reference which reads a variable on its own component or screen updates the live visual when that variable changes. For example, a component with the row `Y = Progress` updates its `Y` each time `Progress` changes. References which read each other run in dependency order, so the order they are written in does not matter. A reference which reads a value applied when the component was created, whether by the screen or by a parent, follows that value. A component which derives from another component also re-evaluates the rows it inherits.

In the following examples, `wave` is a `GraphicalUiElement` created from a component which has the row shown in the first comment. Dependent references update automatically when:

* `SetProperty` sets the variable, such as a custom variable
* A state is applied, including each frame of an animation
* A property of a runtime object is set in code, on the component or on one of its instances, and the property is also a Gum variable

```csharp
// Update
// The component has the row: Y = Progress
wave.SetProperty("Progress", 3f);
```

References between variables in the same screen or component are live. When a variable changes, every row that reads it is updated using the current values on the runtime objects, like a spreadsheet.

References which form a circle are skipped.

If a reference does not follow a change, such as a change made through a property you added to your own class, call `RefreshReferences` with the names of the variables that changed, relative to the component. A name can include an instance, such as `Background.Red`:

```csharp
// Update
// The component has the row: Y = Progress
wave.RefreshReferences("Progress");
```

Nullable variables follow your changes too. Setting a nullable variable back to `null` clears a row which is a plain reference to a variable of a matching type. A row whose expression fails, or which combines values with an operator, keeps its old value.

References to another component, such as a shared `Styles` component, do not update on their own. After changing the other component, call `ApplyAllVariableReferences` and `RefreshStyles`, as described below.

{% hint style="info" %}
Available in November 2026, or now if building Gum from source.
{% endhint %}

## References in Animation Keyframes

A state used as an animation keyframe can hold a variable reference. Gum evaluates the reference against the component every time the animation updates, then interpolates between the evaluated values of the two surrounding keyframes. This lets code offset an animation without editing it.

For example, a component has a custom `float` variable named `OffsetX`. Its `Hidden` state sets `X` to `0` and its `Shown` state sets `X` to `200`, and both states have the reference `X = OffsetX`. Both keyframes then resolve to the current `OffsetX`, so the animation lands wherever `OffsetX` says.

```csharp
// Initialize
component.SetProperty("OffsetX", 50f);
component.PlayAnimation("Show");
```

Changing `OffsetX` while the animation plays takes effect on the next update.

* A keyframe variable with a stored value and no reference behaves as it always has. A keyframe can mix both.
* A plain reference such as `X = OffsetX` works without extra packages. Arithmetic such as `X = 100 + OffsetX` needs [Gum.Expressions](#expression-support-optional).
* A reference that cannot be evaluated leaves the variable at its stored value and is reported once, like any other broken reference.
* Only the keyframe states of the animation that is playing on the component are resolved. Animations of child instances are not.

## Refreshing Live Visuals After Style Changes

If your UI is already on screen and you change style values, you can push those changes to live visuals without re-creating controls. After calling `ApplyAllVariableReferences`, call `RefreshStyles` to re-apply all default state values and Forms visual states recursively.

The simplest approach refreshes all three root containers (Root, PopupRoot, ModalRoot):

```csharp
// Update
// Change style values
var styles = ObjectFinder.Self.GumProjectSave.Components
    .First(item => item.Name == "Styles");
styles.DefaultState.SetValue("Primary.Red", 0);
styles.DefaultState.SetValue("Primary.Green", 128);
styles.DefaultState.SetValue("Primary.Blue", 255);

// Propagate variable references to all ElementSave states
ObjectFinder.Self.GumProjectSave.ApplyAllVariableReferences();

// Push updated values to all live visuals
GumUI.RefreshStyles();
```

You can also target a specific subtree if you know which part of the UI changed:

```csharp
// Update
ObjectFinder.Self.GumProjectSave.ApplyAllVariableReferences();

// Only refresh visuals under a specific element
GumUI.RefreshStyles(myScreenGue);
```

`RefreshStyles` re-applies default state values on every element in the tree and then re-applies the current Forms categorical state (such as Highlighted or Disabled) on each Forms control. This means controls retain their current interaction and runtime state while picking up the new style values.

### Automatic State Preservation

All Forms controls automatically re-apply their current categorical state after `RefreshStyles`. This means any state driven by a Forms property is preserved without any extra work. For example:

* CheckBox `IsChecked` state (checked/unchecked visual)
* RadioButton `IsChecked` and group selection
* ToggleButton `IsChecked` state
* Expander `IsExpanded` state (expanded/collapsed visual)
* ListBox and ListBoxItem selection (`SelectedIndex`, `IsSelected`)
* ComboBox selection
* MenuItem `IsSelected` and `IsHighlighted`
* Button, Label, and all controls' `IsEnabled` / `IsFocused` interaction states

These properties are Forms-level backing fields that are not overwritten by Gum state re-application, so they survive `RefreshStyles` naturally.

### Explicit Value Preservation

Some controls hold runtime values that *are* stored on the visual layer and would be overwritten by default state re-application. These are explicitly saved before the refresh and restored afterward:

* TextBox and PasswordBox caret position and selection
* ComboBox displayed text
* Slider and ScrollBar `Value` (thumb position)
* ScrollViewer scroll offset (both vertical and horizontal)

### Text After RefreshStyles

Controls restore text after `RefreshStyles` only when code supplied it. This covers:

* `Text` on `Button`, `Label`, `ToggleButton` (and so `CheckBox` and `RadioButton`), `TextBox`, and `PasswordBox`
* `Header` on `Expander` and `MenuItem`
* `Placeholder` on `TextBox` and `PasswordBox`

Text counts as supplied by code when you set it through the property or its `NoTranslate` method (such as `SetTextNoTranslate`), when a binding sets it, or when the user types it into a `TextBox`.

Text authored on the Visual is not restored. `RefreshStyles` re-applies it from the Visual, so if you change the authored text (for example through a variable reference), the control shows the new text.

Text set in code does not carry over when you assign a new Visual to a control. The control shows the text the new Visual authors.

{% hint style="info" %}
Available in November 2026, or now if building Gum from source. Before this, `Button`, `Label`, `TextBox`, and `PasswordBox` always restored their text, so a changed authored text was overwritten.
{% endhint %}

## Preserving Custom Runtime Properties

If you set properties at runtime that are not automatically preserved by built-in controls (for example, the size of a resizable panel), you can register them for automatic preservation. Registered properties are captured before `RefreshStyles` re-applies default state values and restored afterward.

The simplest form takes a target object and a property name:

```csharp
// In CustomInitialize
LeftPanel.Width = 300;
this.RegisterRuntimeProperty(LeftPanel, nameof(LeftPanel.Width));
```

You can also register a property on the current control using the shorthand:

```csharp
// In CustomInitialize
this.RegisterRuntimeProperty(nameof(IsEnabled));
```

For computed or transformed values, use the lambda overload:

```csharp
// In CustomInitialize
this.RegisterRuntimeProperty(
    () => ContentPanel.AbsoluteWidth,
    v => ContentPanel.Width = v);
```

Registrations persist for the lifetime of the control. Call `RegisterRuntimeProperty` once during initialization. It does not need to be called again after each refresh.

## Recomputing Values After a Style Refresh

If you need to recompute a value rather than restore it (for example, re-applying localized text after a locale change), subscribe to the `AfterRefreshStyles` event:

```csharp
// In CustomInitialize
void ApplyLocalizedText()
{
    Title.Text = MainMenuTexts.ExperimentalBuild;
    Body.Text  = MainMenuTexts.ThisIsAnExperimentalBuild;
}

ApplyLocalizedText();
this.AfterRefreshStyles += (_, _) => ApplyLocalizedText();
```

A corresponding `BeforeRefreshStyles` event fires before default state values are re-applied, allowing you to capture state if needed.

{% hint style="info" %}
Built-in controls like Label and Button already preserve text you set in code across `RefreshStyles` automatically. You only need `AfterRefreshStyles` when the value should be *recomputed* rather than restored, for example when the locale may have changed between refreshes.
{% endhint %}

## Expression Support (Optional)

By default, variable references support simple dot-path lookups like `Width = OtherInstance.Width`. If your project uses arithmetic expressions in variable references (such as `Width = OtherInstance.Width + 20`), you need to add the `Gum.Expressions` NuGet package and initialize the expression evaluator.

Add the NuGet package:

```
dotnet add package Gum.Expressions
```

Then call `UseExpressions` at startup:

```csharp
// Initialize
GumUI.UseExpressions();
```

{% hint style="info" %}
Available in preview NuGet packages (use a `-preview` version), or now if building Gum from source.
{% endhint %}

{% hint style="info" %}
The `Gum.Expressions` package uses Microsoft Roslyn for expression parsing, which adds approximately 10 MB to your build output. If your variable references only use simple assignments between variables of the same type (no arithmetic), you do not need this package. See [Casting and Type Considerations](#casting-and-type-considerations).
{% endhint %}

The same `Gum.Expressions` package also enables runtime evaluation of arithmetic (including modulo `%`), conditional (ternary), comparison (`==`, `!=`, `<`, `>`, `<=`, `>=`), and logical (`&&`, `||`, `!`) operators, plus math functions such as `Sin`, `Max`, and `Clamp`, in variable references. Position among siblings (`Index`) and the `Absolute` variables (such as `AbsoluteWidth`) also need the package. See the [Variable References](https://docs.flatredball.com/gum/gum-tool/gum-elements/general-properties/variable-references.md) page for the full list of supported syntax.

Live updates within a component work without the package for plain references such as `Y = Progress`. Rows with expressions need `UseExpressions()` to update live.

A reference which reads `global::Localization.CurrentLanguage` re-evaluates on live visuals when `CurrentLanguage` changes, so a row such as `Width = global::Localization.CurrentLanguage == 2 ? 220 : 160` follows a language switch without extra code. See [Localization](https://docs.flatredball.com/gum/code/localization.md) for switching languages.

{% hint style="info" %}
Available in November 2026, or now if building Gum from source.
{% endhint %}

If you are linking to Gum source instead of NuGet, see the setup page for your platform for instructions on adding GumExpressions as a project reference:

* [MonoGame/KNI/FNA Setup](https://docs.flatredball.com/gum/code/getting-started/setup/adding-initializing-gum/monogame-kni-fna.md)
* [Raylib Setup](https://docs.flatredball.com/gum/code/getting-started/setup/adding-initializing-gum/raylib-raylib-cs.md)

## Casting and Type Considerations

Each variable has a type, such as `float` for `X` or `int` for `FontSize`, which is the type your project saves it as. A reference writes its result to the variable on the left, so the result has to fit that type. How Gum handles this depends on whether `Gum.Expressions` is initialized.

### Without Gum.Expressions

A plain reference such as `XUnits = Source.XUnits` copies the value exactly, including values that only code can set. `PercentageOfFile`, `PercentageOfOtherDimension`, and `MaintainFileAspectRatio` on `XUnits` and `YUnits` carry over, and so does a fractional `FontSize` such as `12.5`.

Without the package, the variable on the right and the variable on the left must have the same type. When they differ, such as `Width = Source.IsBold`, the variable on the left keeps its current value and Gum reports an error that names the reference. The error appears as a `[Gum]` line on `Console.Error` and through `CustomSetPropertyOnRenderable.PropertyAssignmentError`, once for each broken reference on each component.

The error tells you to add `Gum.Expressions` when it converts that pair: `int`, `float`, and `double` among themselves, any value into a `string`, and a `string` into an enum. A pair it cannot convert, such as a `bool` or `string` into a number or a number into a `bool`, gets an error that says so. A `FontSize` accepts an `int` or a `float`, and an enum variable accepts an `int`, so those references apply as written.

### With Gum.Expressions

After you call `UseExpressions()`, Gum evaluates the right side of every reference, plain ones included, and converts the result to the type of the variable on the left. The same conversion applies when you call `ApplyAllVariableReferences`.

| Right side result                                               | Left side variable                     | What happens                                                                                                                                                                                                               |
| --------------------------------------------------------------- | -------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `float` or `double`                                             | `int`                                  | The fraction is dropped toward zero. `3.7` becomes `3` and `-3.7` becomes `-3`.                                                                                                                                            |
| `int` or `double`                                               | `float`                                | Converted to `float`.                                                                                                                                                                                                      |
| `int` or `float`                                                | `double`                               | Converted to `double`.                                                                                                                                                                                                     |
| Any value                                                       | `string`                               | The value's text. `42` becomes `"42"`.                                                                                                                                                                                     |
| Text such as `"LeftToRightStack"`                               | Enum, such as `ChildrenLayout`         | Converted to the enum value with that name. Capitalization does not matter.                                                                                                                                                |
| Whole number                                                    | Enum                                   | Converted to the enum value with that number.                                                                                                                                                                              |
| `XUnits` or `YUnits` value set in code                          | `XUnits` or `YUnits`                   | Kept exactly, including `PercentageOfFile`.                                                                                                                                                                                |
| Text or a `bool`                                                | A number (`int`, `float`, or `double`) | The reference is not applied, Gum reports an error that names the reference (once for each broken reference on each component), and the variable keeps its current value. Text such as `"12"` is not turned into a number. |
| Anything else that does not fit, such as a number into a `bool` | Any                                    | The reference is not applied, Gum reports an error that names the reference (once for each broken reference on each component), and the variable keeps its current value.                                                  |

A fractional `FontSize` is the one value that does not carry over unchanged. `FontSize` is saved as an `int`, so the result of a reference is truncated when Gum writes it to `FontSize`. A `FontSize` of `12.5` set in code is read as `12.5` inside an expression, but a plain `FontSize = Source.FontSize` writes `12`. The same truncation applies to any fractional result written to an `int` variable.

For nullable variables, see the nullable paragraph in [Live Updates Within a Component](#live-updates-within-a-component).

When a reference produces `NaN` or infinity for a `float` or `double` variable, Gum reports an error that names the reference and the variable keeps its current value, with or without `Gum.Expressions`. The exception is `MinWidth`, `MaxWidth`, `MinHeight` and `MaxHeight`, which treat `NaN` or infinity as no limit. With `Gum.Expressions`, a `float` or `double` outside the range of an `int` is reported the same way when the variable is an `int`.

### Working With Types

* Use whole numbers for variables saved as `int`.
* To round instead of drop the fraction, wrap the right side in `Round`, `Floor`, or `Ceiling`, such as `FontSize = Round(Source.FontSize * 1.5)`. These are listed under [Math Functions](https://docs.flatredball.com/gum/gum-tool/gum-elements/general-properties/variable-references.md#math-functions).
* To pick an enum value from a reference, add `Gum.Expressions` and use the value's name as text. See [Enum Assignment](https://docs.flatredball.com/gum/gum-tool/gum-elements/general-properties/variable-references.md#enum-assignment).
* To use a fractional `FontSize`, set it in code instead of through a reference, as shown below.

```csharp
// Initialize
text.FontSize = 12.5f;
```

{% hint style="info" %}
Available in November 2026, or now if building Gum from source.
{% endhint %}


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.flatredball.com/gum/code/styling/runtime-variable-references.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
