Understanding Visual State Manager in Xamarin Forms

Visual State Manager is a concept that was introduced in Xamarin Forms 3.0 which allows you to do visual changes according to a state. So basically according to a status change, you can change the properties of any UI control.

By default, it has 3 pre-defined states: Normal, Disabled, Focused. A good use case then is when using an entry, Why? Because the entry already supports these states by definition.

For example, if you want to change the color of an entry when it’s focused, you just have to add the VisualStateManager.VisualStateGroups property and change the style for each state.

The result will be:

Also, you can define those states using styles. That way if you want to apply the same VisualState to all the entries, you can define it as a global style in the App.xaml:

Custom State

So what happens if you want to use another control and doing something more custom like changing the Label FontSize when a Label has been tapped or not. For this use case, you can create your own VisualState by doing the following:

1- Use property VisualStateManager.VisualStateGroups

2-Add the VisualStateGroups using the x:Name you want

3-Add the style for each state

Now to change the state of the Label you have to do it in code-behind. If I want to change the status to Selected when the label has been clicked and change it to UnSelected when it isn’t, you can do it with the following code:

VisualStateManager.GoToState(<Element you want to change the state>, <New State>”);

Real-life use cases

Here are some use cases to make use of it:

  • If you want to change all your app controls when the app has changed to one state (For example, the app is being used at night, change the color of all the controls).
  • If you rotate your device to adapt the UI elements.
  • If you want to change a control appearance according to a specific state. For example, if an element has been selected/unselected.

I did this sample using a pre-defined focused/unfocused state for the entry. Also created a new state to trigger when the month day is selected:

You can find the full source code here.

Happy coding!

References

You may also like

1 Comment