Monday, June 30, 2008

VSM Strangeness

The Problem
While migrating a Silverlight 2 Beta 1 control to Beta 2, I encountered some odd behavior with the VisualStateManager and I thought I would document my experience in the event that you might run into the same issue.  From what I can tell, this only occurs when you have multiple instances of a control that change state by animating color properties (ColorAnimation).  There may be other ways to induce this behavior, but the following is the only way I have encountered personally.  Simply put, calling VisualStateManager.GoToState to does not always go to the correct state in some cases, even though no exception is thrown and a true boolean value is returned.

After spending way too much time trying to find a bug in my code that didn't really exist, I submitted a post to the Silverlight forums.  The response I got back from Microsoft is that in Beta 2, there are issues with the VSM and sharing resources (like Brushes).  The result is random glitches state transitions. 

A Demonstration
To reproduce the issue, I built a small control that contains a series of spheres.  These spheres are supposed to turn on in sequence.  In other words, if you mouse-over the 3rd sphere, the 3rd sphere  and each of the spheres prior to the 3rd sphere will light up.  All spheres after the third sphere will remain off.  Now, at first glance, moving your mouse around the control works as expected, but after moving your mouse around for a while, the spheres will begin to switch to the incorrect states.  See the screenshots below:

 

Live Demo

Source Code

The Workaround
So, the workaround for now is to avoid animating the colors as I have in the control above.  One solution is to build your XAML in such a way that you have an ON Object and an OFF Object.  Then on the mouse enter and mouse leave event, toggle the the opacity for the objects accordingly.  The major downside to this is that you have to maintain two identical objects in your XAML which can be a maintenance nightmare if you are animating Path objects.

The Fix
According to Microsoft, this is a known issue and I am certain it will be fixed in the next drop.  Until then, happy coding!