How to use Behaviors in WPF


Hello. Today I will show you how to use very useful feature of WPF called behavior. Behavior is peace of reusable functionality that you can attach to any element in UI tree. Let’s get started from simple example.

First of all download Expression Blend SDK and install it.

Behavior comes from System.windows.interactivity.dll library located in mentioned above Expression Blend SDK, thus you need change your project to reference it.

For the sake of example let’s create very simple behavior specifically for TextBox that will just show message box with text whenever related TextBox loses focus:

public class ShowMessageOnLostFocusBehavior : Behavior<TextBox> { protected override void OnAttached() { AssociatedObject.LostFocus += AssociatedObjectOnLostFocus; base.OnAttached(); } protected override void OnDetaching() { AssociatedObject.LostFocus -= AssociatedObjectOnLostFocus; base.OnDetaching(); } private void AssociatedObjectOnLostFocus(object sender, RoutedEventArgs routedEventArgs) { MessageBox.Show(AssociatedObject.Text); } }

As you can see behaviors need to inherit from Behavior class and specify type of element it must be attached to as generic parameter. Then I used two methods – OnAttached and OnDeatched to attach and detach my event handler. These methods will run whenever behavior is attached to or detached from element in UI tree.

Next create two text boxes and attach behavior to them:

<Grid> <StackPanel> <TextBox Width="70" Height="30"> <i:Interaction.Behaviors> <WPFBehaviorsSample:ShowMessageOnLostFocusBehavior/> </i:Interaction.Behaviors> </TextBox> <TextBox Width="70" Height="30"> <i:Interaction.Behaviors> <WPFBehaviorsSample:ShowMessageOnLostFocusBehavior/> </i:Interaction.Behaviors> </TextBox> </StackPanel> </Grid>

Now, whenever text box loses focus message box will be shown by behavior attached this text box.

Remember that behaviors should be used in case you need to provide some functionality which requires state that comes from multiple sources. If you have requirements for more granular functionality like in this article you should use Actions which I will describe in next article.

Advertisements