githubEdit

View Model Property Dependency

Introduction

Gum's ViewModel supports using the DependsOn attribute to define dependencies between properties. By using this attribute, changes in one property can result in changes to other properties. The same property can be used as a dependency for multiple properties, allowing changes to one property resulting in many pieces of UI being updated.

Code Example: Using DependsOn

The following code shows how a single variable can be used to update multiple UI properties. First we can declare a ViewModel using DependsOn to make IsBrokeTextVisible and MoneyDisplay depend on Money.

class PlayerViewModel : ViewModel
{
    public int Money
    {
        get => Get<int>();
        set => Set(value);
    }

    [DependsOn(nameof(Money))]
    public bool IsBrokeTextVisible => Money <= 0;

    [DependsOn(nameof(Money))]
    public string MoneyDisplay => $"${Money:N0}";
}

We can use the PlayerViewModel to update the UI in response to Money changing. The following block of code shows how to do so in a code-only project.

If this code were in a Screen defined in Gum with code generation, the code might look like the following block:

Two buttons updating money

Last updated

Was this helpful?