Silverlight 3.0 Behaviors – Part 1

In this post I will start exploring behaviors in Silverlight 3.0.  This topic is very large, and it will take me a few posts to cover at least key aspects of behaviors.

A little background on the subject.  Silverlight, unlike WPF does not natively support triggers that would allow the developer to change UI based on criteria or data.  In Silverlight 3.0 we now have a facility to support similar behavior.  One key usage scenario for behaviors is to allow a designer to support UI changes based on user actions without writing any code.

To extend an existing behavior base class we need to add a reference to System.Windows.Interactivity DLL.  We will start with a simple behavior.  By default Silverlight Textbox does not select all the text when it gets focus.  This however us a desirable behavior from a user perspective in many scenarios.  So, for our first excursion into Silverlight behaviors we will write “Select All Text On Focus in Textbox” behavior.

We will start by extending an existing class in SilverlightTargetedTriggerAction<C>.  In our case we are supplying generic type for our behavior – Textbox – TargetedTriggerAction<TextBox>. 

We are specifying Textbox as the target type for our behavior.  Typically, we would specify an action and an event that would invoke the action on the behavior.  In our case we however want to make sure that they only event that invokes the behavior is GotFocus event.  So, we are leaving our Invoke method blank.  Here is the final version of the class:

using System;

using System.Windows.Controls;

using System.Windows.Interactivity;

 

namespace Behaviors

{

    public class SelectOnFocusAction : TargetedTriggerAction<TextBox>

    {

        protected override void OnAttached()

        {

            base.OnAttached();

            Target.GotFocus += Target_GotFocus;

        }

 

        void Target_GotFocus(object sender, System.Windows.RoutedEventArgs e)

        {

            Target.SelectAll();

        }

        protected override void OnDetaching()

        {

            base.OnDetaching();

            Target.GotFocus -= Target_GotFocus;

        }

 

        protected override void Invoke(object parameter)

        {

            //do nothing

            // we are handling specific event we are interested in

            // by attaching events to the target text

        }

       

    }

}

 

You can download the sample project with this behavior and text page here.

Leave a Reply

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