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);



Deploying Azure Web App Certificates from Key Vault

How to work around an ARM template limitation when using a Key Vault certificate in a Web App

View details »


Roku Round-up

Quick updates on some Roku libraries that I recently released

View details »


CORS and exceptions on ASP.NET Core

How to ensure your CORS headers are properly returned with HTTP error responses on ASP.NET Core

View details »


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 »

More Posts >