Xaml VisualStateManager weirdness

Sometimes GoToState() just wont work or works intermittently. Here is a note to myself with the answer.

This is more a note to my future self, but maybe some other folks will find it helpful as well.

Recently, I was developing a custom templated control in a Windows Phone app and the template defined several VisualStates. In the control's code, I used the VisualStateManager.GoToState() method to switch between the states when necessary. However, sometimes the state would not change. It wasnt reproducible consistently - sometimes it would change states back and forth just fine, and other times it would not change states at all.

After much debugging, lots of trial-and-error, and finally a bit of a revelation, I discovered the root cause:

If you call VisualStateManager.GoToState() before OnApplyTemplate() has ran, it seems to corrupt the VisualStateManager and subsequent attempts to change state will become erratic.

In my particular case, I had bound some properties in the template to DependencyProperties in the control and was using the PropertyChangedCallback to update the visual state. However, this meant that databound values were set on the control early in its lifecycle and causes this issue to occur.

The fix for me was to simply ignore any calls to my internal UpdateState() method until OnApplyTemplate() had been called and then to update the state based on the current property values:

public override void OnApplyTemplate()
    hasLoaded = true;

void UpdateState(bool isActive)
    if (hasLoaded)
        string state = isActive ? "Active" : "Inactive";
        System.Windows.VisualStateManager.GoToState(this, state, true);



The many uses of Azure Functions Proxies

Azure Functions Proxies are awesome - here are just a few ways to leverage them

View details »


Build an Alexa skill using Azure Functions

Although AWS Lambdas are the default, it is dead simple to use Azure Functions for your Alexa skill as well

View details »


Roll Your Own React

(on Roku, just for an added twist)

View details »


Streaming live drone footage using Azure Media Services

Directly from your drone to the world, via the the cloud

View details »


Redux + Roku = Redoku

Making Roku development less painful by making state changes more predictable

View details »

More Posts >