Skip to content
Tutorials Center
My learning

Topics

Lesson 32 of 42 ยท Styling and Resources

Visual States and Triggers

Change how .NET MAUI controls look in response to state with VisualStateManager, property, data, event and multi triggers, and learn how to model states in testable C#.

A button looks one way when it is idle, another when pressed, and another when disabled. A text field turns red when the input is invalid. In MAUI you describe these changes declaratively instead of writing if statements in code-behind. Two tools do the job: the VisualStateManager (VSM), which switches between named states, and triggers, which react to a property value, a binding or an event.

The XAML and MAUI APIs are shown read-only because the site cannot run a MAUI app. The runnable examples are plain C# stand-ins that model the same decision logic, so you can see how states are chosen and test them.

Visual states

A visual state group contains mutually exclusive states. A control is in exactly one state of a group at a time. Controls ship with a group called CommonStates that holds Normal, Disabled, Focused, PointerOver and Pressed (not every control uses all of them).

XML
<Style TargetType="Button">
    <Setter Property="VisualStateManager.VisualStateGroups">
        <VisualStateGroupList>
            <VisualStateGroup x:Name="CommonStates">
                <VisualState x:Name="Normal">
                    <VisualState.Setters>
                        <Setter Property="BackgroundColor" Value="#512BD4" />
                    </VisualState.Setters>
                </VisualState>
                <VisualState x:Name="Pressed">
                    <VisualState.Setters>
                        <Setter Property="BackgroundColor" Value="#3A1F9E" />
                        <Setter Property="Scale" Value="0.97" />
                    </VisualState.Setters>
                </VisualState>
                <VisualState x:Name="Disabled">
                    <VisualState.Setters>
                        <Setter Property="BackgroundColor" Value="#C8C8C8" />
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateGroupList>
    </Setter>
</Style>

Put this in a style (see Resources and Styles) and every button of the app gets press feedback. When the state changes, MAUI applies the setters of the new state and undoes the setters of the old state, restoring the values the control had before. That is why you do not write a "reset" for each state.

Your own states

You can add groups and move a control into any state from code. This is useful for a page-level state such as Loading, Content and Error:

XML
<ContentPage ...>
    <VisualStateManager.VisualStateGroups>
        <VisualStateGroupList>
            <VisualStateGroup Name="ScreenStates">
                <VisualState Name="Loading">
                    <VisualState.Setters>
                        <Setter TargetName="Spinner" Property="ActivityIndicator.IsRunning" Value="True" />
                        <Setter TargetName="List" Property="CollectionView.IsVisible" Value="False" />
                    </VisualState.Setters>
                </VisualState>
                <VisualState Name="Content">
                    <VisualState.Setters>
                        <Setter TargetName="Spinner" Property="ActivityIndicator.IsRunning" Value="False" />
                    </VisualState.Setters>
                </VisualState>
            </VisualStateGroup>
        </VisualStateGroupList>
    </VisualStateManager.VisualStateGroups>
    <!-- ... controls named Spinner and List ... -->
</ContentPage>
C#
VisualStateManager.GoToState(this, "Loading");
// later
VisualStateManager.GoToState(this, "Content");

In an MVVM app the view model does not know about the view, so a small property changed handler (or the Community Toolkit's StateContainer) calls GoToState for it. Keep the decision in the view model as an enum, and let the view map the enum to a state name.

State machines in plain C#

The enum-to-state idea is easy to test. Here a screen has three states and a tiny set of rules for which transitions are allowed:

C# Stand-in: a screen state machine

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

A switch over (state, event) pairs makes illegal transitions impossible to miss, and the view only needs GoToState(Current.ToString()).

Adaptive layouts with states

States are not limited to colors. A common use is AdaptiveTrigger-like behavior: switching between a one-column and a two-column layout depending on the window width. MAUI has AdaptiveTrigger for Windows-style apps, and on phones and tablets you often react to SizeChanged and call GoToState("Wide") or GoToState("Narrow") yourself. Decide with a method such as:

C#
static string LayoutFor(double width) => width switch
{
    < 600 => "Narrow",
    < 1000 => "Medium",
    _ => "Wide"
};

Triggers

Triggers are simpler than states. They live in a control's (or style's) Triggers collection and set properties when a condition holds, undoing them when it stops holding. MAUI has four kinds.

Property trigger

Reacts to a property of the same control:

XML
<Entry Placeholder="Name">
    <Entry.Triggers>
        <Trigger TargetType="Entry" Property="IsFocused" Value="True">
            <Setter Property="BackgroundColor" Value="#FFF8E1" />
        </Trigger>
    </Entry.Triggers>
</Entry>

Data trigger

Reacts to a binding, so it can watch a view model:

XML
<Label Text="Offline">
    <Label.Triggers>
        <DataTrigger TargetType="Label" Binding="{Binding IsOnline}" Value="False">
            <Setter Property="TextColor" Value="Red" />
        </DataTrigger>
    </Label.Triggers>
</Label>

A very common data trigger shows a validation color when a text length is wrong: Binding="{Source={x:Reference nameEntry}, Path=Text.Length}" Value="0".

Event trigger

Runs C# code when an event fires. It needs a small TriggerAction<T> class:

C#
public class ShakeTrigger : TriggerAction<VisualElement>
{
    protected override async void Invoke(VisualElement sender)
    {
        for (int i = 0; i < 4; i++)
        {
            await sender.TranslateTo(i % 2 == 0 ? -8 : 8, 0, 40);
        }
        await sender.TranslateTo(0, 0, 40);
    }
}
XML
<Entry>
    <Entry.Triggers>
        <EventTrigger Event="Unfocused">
            <local:ShakeTrigger />
        </EventTrigger>
    </Entry.Triggers>
</Entry>

Multi trigger

Combines several conditions with AND logic. A typical use is enabling the Save button only when every field is filled in:

XML
<Button Text="Save" IsEnabled="False">
    <Button.Triggers>
        <MultiTrigger TargetType="Button">
            <MultiTrigger.Conditions>
                <BindingCondition Binding="{Binding Source={x:Reference nameEntry}, Path=Text.Length}" Value="3" />
                <BindingCondition Binding="{Binding Source={x:Reference emailEntry}, Path=Text.Length}" Value="5" />
            </MultiTrigger.Conditions>
            <Setter Property="IsEnabled" Value="True" />
        </MultiTrigger>
    </Button.Triggers>
</Button>

Note that a trigger compares for equality. "Length of at least 3" is not expressible with DataTrigger alone; use a view model property such as IsNameValid instead and trigger on that. That leads to a good rule of thumb.

States, triggers or view model?

Need Best tool
Press, focus, disabled feedback VisualStateManager (CommonStates)
Screen-level modes (loading, error) VisualStateManager with your own group
One property reacts to one value Trigger
Validation with rules View model property (IsValid) plus a data trigger or style
Reusable look across the app Style with VisualStateGroups or Triggers

Logic that you want to unit test belongs in C# (view model). The XAML then only maps the result to colors.

Putting a validation rule to work

Here a form decides which fields are valid and which visual state each should be in. The XAML in a real app would bind Valid/Invalid to a DataTrigger; here only the logic runs.

C# Stand-in: field validation drives the visual state

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Common mistakes

  • Defining the same property in two states of different groups: the group that changes last wins, which is confusing. Use one group per concern.
  • Forgetting that a trigger only checks equality.
  • Using DataTrigger on a binding without TargetType; the XAML will not compile.
  • Doing heavy work inside TriggerAction.Invoke. Triggers run on the UI thread.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What happens to a state's setters when the control moves to another state in the same group?

    The VisualStateManager reverts the old state's setters before applying the new state's, so you never write reset code.
  2. 2. Which trigger lets a Label react to a property of a view model?

    A DataTrigger uses a binding, so it can watch anything you can bind to. A plain Trigger only watches a property of the same control.
  3. 3. How do you require two conditions at once before a Setter applies?

    MultiTrigger evaluates all of its conditions with AND logic and applies its setters only when every one holds.
  4. 4. Where should the rule 'name has at least 3 characters' live so you can unit test it?

    Triggers compare for equality only, and XAML cannot be unit tested easily. A C# property holds the rule and the XAML maps its value to a look.

Summary

  • A visual state group holds exclusive states; the manager applies the new setters and undoes the old ones.
  • Use CommonStates for press and disabled feedback and your own groups for screen modes; switch with VisualStateManager.GoToState.
  • Triggers (property, data, event, multi) are simpler and compare values for equality.
  • Keep decisions in C# (an enum or boolean on the view model) and let XAML map them to appearance.

Next: Fonts, Images and Icons