Home > Scrum Sprint Monitor, Tips > Animating a data-bound color property

Animating a data-bound color property

As I was going through the UI of the Scrum Sprint Monitor to introduce animations to the larger UI elements, one type of property was proving difficult to animate: the dynamic background color of some elements which were bound to Brush (or Color) properties of the ViewModel.

Picture this: you have a Color property that is currently Green. At some point it changes to Red. You would like the UI to update smothly, so you would not see the color jump from Green to Red. You are not able to do this in XAML with triggers and storyboards directly. The problem lies in the fact is that the Animation objects in XAML cannot be bound to dynamic values (see instances here and here), as they must be frozen for performance and thread safety reasons.

<DataTemplate DataType="{x:Type ViewModels:BuildStatusBackgroundViewModel}">
    <Grid Background="{Binding Path=BuildStatusColor}" />
</DataTemplate>

Therefore there is no point in trying to introduce triggers (be it EventTriggers or DataTriggers) in this Grid element. What I ended up doing is deriving a class from Grid and spawning the animation from code behind.

<DataTemplate DataType="{x:Type ViewModels:BuildStatusBackgroundViewModel}">
    <Controls:BuildStatusBorder />
</DataTemplate>

See the code-behind example here. I did encounter a pitfall while developing this approach. I ran into a “Cannot freeze this Storyboard timeline tree for use across threads” exception, when the animation was kicked off. I fixed this by cloning the existing property value, essentially removing any data binding from the property.

Hope this helps someone who is running into the same problem of animating transitions between databound properties!

Shout it

Share and Enjoy:
  • Digg
  • del.icio.us
  • DotNetKicks
  • DZone
  • Technorati
  • LinkedIn
  • Google Bookmarks
  • StumbleUpon
  • email
  • Print
  1. No comments yet.
  1. August 17th, 2009 at 10:25 | #1