Archive for September, 2011

Creating Behaviors for WP7 Silverlight controls

September 29, 2011 1 comment

Behaviors allow you attach custom behavior to Silverlight controls from within the XAML instead of having to add code to the code-behind of the view. Support for behaviors can be added by referencing the assembly “System.Windows.Interactivity” from within your Windows Phone project.

Creating a new behavior is straightforward. All you have to do is extend the generic Behavior class and choosing a Dependency type for the generic parameter T. You can add custom behavior in the “OnAttached” and “OnDetaching” methods.

The following sample is a behavior I created for a search box in Cloudfox. The binding is automatically updated when the user presses enter.

public class UpdateOnSearchBehavior: Behavior<TextBox>
    protected override void OnAttached()

        this.AssociatedObject.KeyDown += new KeyEventHandler(AssociatedObject_KeyDown);

    protected override void OnDetaching()

        this.AssociatedObject.KeyDown -= new KeyEventHandler(AssociatedObject_KeyDown);

    private void AssociatedObject_KeyDown(object sender, KeyEventArgs e)
        if (e.Key == Key.Enter)
            BindingExpression binding = this.AssociatedObject.GetBindingExpression(TextBox.TextProperty);

            // Set the focus back to the page instead of the TextBox
            PhoneApplicationPage currentPage = ((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage;
            if (currentPage != null)

The behavior can be added to a TextBox using the following XAML:

<TextBox InputScope="Search" Text="{Binding SearchText, Mode=TwoWay}" Name="searchTextBox">

Please note: Don’t forget to add a reference to System.Windows.Interactivity in the XAML of the View: