Creating Behaviors for WP7 Silverlight controls
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()
{
base.OnAttached();
this.AssociatedObject.KeyDown += new KeyEventHandler(AssociatedObject_KeyDown);
}
protected override void OnDetaching()
{
base.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);
binding.UpdateSource();
// Set the focus back to the page instead of the TextBox
PhoneApplicationPage currentPage = ((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage;
if (currentPage != null)
currentPage.Focus();
}
}
}
The behavior can be added to a TextBox using the following XAML:
<TextBox InputScope="Search" Text="{Binding SearchText, Mode=TwoWay}" Name="searchTextBox">
<i:Interaction.Behaviors>
<util:UpdateOnSearchBehavior/>
</i:Interaction.Behaviors>
</TextBox>
Please note: Don’t forget to add a reference to System.Windows.Interactivity in the XAML of the View:
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
Source: http://pieterderycke.wordpress.com/2011/09/29/creating-behaviors-for-wp7-silverlight-controls/
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)





