VisualStateManager pitfalls

VisualStateManager is extremely useful when building XAML layouts. With UWP’s AdaptiveTriggers to switch between states it provides a great way to build design that looks great on any screen size. There are however two small gotchas that can cause unnecessarily long periods of head scratching.

Gotcha 1: VisualStateManger placement

Consider the following snippet:

When you try to use this code, you will notice, that the state is never activated (the text of the TextBlock  doesn’t change when the Window width is greater than 700).

The reason for this is that VisualStateManager  cannot be attached to the root ( Page , UserControl , …) but has to be attached to a control or panel. Wrapping VisualStateManager  inside the main Content  UI element is the most common solution:

Gotcha 2: Invalid setters

Suppose we have the following:

At first glance it seems that everything is ok. At the second glance you can notice an innocent typo in the setter target for TargetText.Foreground. You might think that this will surely be discovered at runtime as an exception. But surprisingly that is not the case.

When the Target  or Value  of any Setter  is invalid, the app will still run without exceptions, but the VisualState  containing this Setter  will never be applied. In this concrete example, neither the Foreground  nor the Text  will change when the window is wider than 700.

Whenever you encounter a VisualState , which does not take effect, be sure to check twice whether all the Setters  are actually valid. You may also try to comment the whole Setters  block and then try uncommenting one-by-one to find the culprit.

Sample source code

Source code for this blog post is available on my GitHub.


VisualStateManager  is very useful and makes creating complex adaptive layouts much easier. We must however remain cautious to use it as intended and avoid misspellings at least until the Visual Studio XAML editor get proper IntelliSense support for Setter ‘s Target  and Value .

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">