githubEdit

Binding Visual Properties

Introduction

Visual properties can be directly bound, either directly bound to properties on a ViewModel, or through custom properties on the Forms control. This section discusses the multiple ways that binding can be performed on visuals.

circle-exclamation

Binding Visual Properties Directly

Visual properties can be bound directly. For example, the following code shows how to bind the width of a Button to a ButtonWidth property on a ViewModel.

// assume MyButton is a valid button
var buttonVisual = MyButton.Visual;
buttonVisual.SetBinding(
    nameof(buttonVisual.Width),
    nameof(ViewModel.ButtonWidth));

If the property requires a specific type, then the Visual can be casted to access type-specific properties, as shown in the following code block:

// This assumes the project is code-only
var buttonVisual = (ButtonVisual)MyButton.Visual;
var text = buttonVisual.TextInstance;
text.SetBinding(
    nameof(Text.FontScale),
    nameof(ViewModel.ButtonFontScale));

Binding Converter Properties (Code Generation)

If your project uses the Gum tool and code generation, then each component and screen has a custom code file which can contain converter properties that can be bound. This allows ViewModels to avoid adding view-specific properties.

For example, consider a screen named GameScreenHud which contains a single label named HealthLabel.

The ViewModel may contain general properties such as CurrentHealth and IsLowHealth, but the view can process these properties to display the health with a prefix, and to modify the Label property.

The following code could be added to GameScreenHud.cs, which is the custom code file created when the GameScreenHud is generated:

Binding to States (Code Generation)

If your project uses code generation, enums are automatically created for every category in your screens and components. The current state for each category can be bound to a ViewModel property. This can be done by adding a type to your ViewModel, or through a binding converter property.

For this example, consider a component named ComponentWithState which has a SizeCategory with two states: Large and Small.

This component generates an enum similar to the following block (you do not need to write this):

Similarly, the generated code also includes a property which can be bound:

The ViewModel can directly contain a property of type SizeCategory, or a more abstract property can be used with a binding converter property in the custom code. Which you choose depends on how you like to organize your code.

This requires an extra property in the custom code for the component:

Last updated

Was this helpful?