Visual State Manager or rather Behavior ? (part 3)

So far, so good. I created a little application indicating the distance to my geographically closest friend. I used Visual State Manager for making my indicator change, depending on the distance I get from the Distance-service. It takes some practice to get used to it. Now, I have two little problems with VSM:

  • It's a lot to write, even for having a simple control like our distance-indicator.
  • Changes (e.g. adding another state) always have to be done in two locations : code and XAML.

Now, when using Blend, you might have seen Behaviors, which you can drag and drop on top of your controls. They add some, ehm 'Behavior' to these controls. It also adds a specific assembly needed for creating these Behaviors, i.e. Microsoft.Phone.Interop. Next to a few out-of-the-box behaviors that Blend provides, you can start creating your own Behaviors. And the way of doing that, is just child's play. Simply create your own class, inheriting from Behavior<T> with T being the control for which you create a behavior. Of course, nothing stops you from using FrameworkElement here.

I keep it simple, and I create a Behavior for the Ellipse. I also create 3 properties for specifying the colors for my distance-indicator:

   1:  public class DistanceBehavior : Behavior<Ellipse>
   2:  {
   3:      protected override void OnAttached()
   4:      {
   5:          base.OnAttached();
   7:          Ellipse ao = AssociatedObject as Ellipse;
   8:          DistanceReader.DistanceChanged += (s, ea) =>
   9:          {
  10:              if (ea.Distance>5)
  11:              {
  12:                  ao.Fill = this.FarColor;
  13:              }
  14:              else if (ea.Distance>2)
  15:              {
  16:                  ao.Fill = this.AverageColor;
  17:              }
  18:              else
  19:              {
  20:                  ao.Fill = this.CloseColor;
  21:              }
  22:          };
  23:      }
  25:      public Brush FarColor { get; set; }
  27:      public Brush AverageColor { get; set; }
  29:      public Brush CloseColor { get; set; }
  30:  }


Let's now use this behavior on an ellipse we add to our MainPage. We first need to add the necessary namespaces to our xaml:


(!! I'm only showing the my-namespace here for completeness. Since we already added it to App.xaml in Part 1, we don't need to add it here).

Let's now add our ellipse, and give it our Behavior :

        <my:DistanceBehavior FarColor="Red" AverageColor="Orange" CloseColor="Green"/>

Test your application again, and you'll see your ellipse change in the same way as your VSM-control, but this time with less coding and (in my opinion) easier to maintain.