Author : Admin
Last Modified : 07-Nov-2021
Complexity : Beginner

Introduction of Behaviors in WPF


Behaviors encapsulate the pieces of functionality into a reusable component, so that can attach to an element.
To be more clear - Suppose we have a Text box, and the requirement is when there is data in the text box the background will be green otherwise white.

for simply without behavior we can achieve this by writing some event and code for this, but if the same this is needed for many Text boxes for different UI, we need to write the code again and again. (It is a very simple example but a real scenario can be more complex)
The Behavior just wraps this functionality and can be attached with an element if needed.

Behavior introduces in Expression Blend 3 (System.Windows.interactivity.dll)

 

Benefit

  • Behavior is to provide additional functionalities and extensibility to controls without writing code behind
  • Behaviors also have the benefit of keeping the MVVM pattern intact, since we can move code from code behind to behaviors.
  • Behavior is a reusable component, write once and use later as much time is required.

 

Implementation

To create a Behavior Just drive your class with Behavior<T>(Behavior Generic class) and there is a method OnAttached to override it.

Behavior is the base class for providing attachable states and commands to an object. The types the Behavior can be attached to can be controlled by the generic parameter. Override OnAttached() and OnDetaching() methods to hook and unhook any necessary handlers from the AssociatedObject.(Source MSDN)

public abstract class Behavior<T> : Behavior where T : DependencyObject

There are two important methods OnAttached() and OnDetaching() in the Behavior class, this can be overridden to implement Behavior. Behavior can be simple and with command.
E.g
Lets we have a situation where we need Textbox, if there is data the background turn to Green otherwise it is Red.

Create a Behavior class TextChangeBehavior.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interactivity;
using System.Windows.Media;
namespace BehavoiurTest
{
   public class TextChangeBehavior : Behavior<TextBox>
   {
       protected override void OnAttached()
       {
           base.OnAttached();
          TextBox txtBox= AssociatedObject as TextBox;
          txtBox.TextChanged += txt_TextChanged;
          if (string.IsNullOrEmpty(txtBox.Text))
          {
              txtBox.Background = new SolidColorBrush(Colors.Green);
          }
          else
          {
              txtBox.Background = new SolidColorBrush(Colors.Red);
          }
          
       }
       void txt_TextChanged(object sender, TextChangedEventArgs e)
       {
           TextBox txtBox = AssociatedObject as TextBox;
           txtBox.TextChanged += txt_TextChanged;
           if (string.IsNullOrEmpty(txtBox.Text))
          {
              txtBox.Background = new SolidColorBrush(Colors.Green);
          }
          else
          {
              txtBox.Background = new SolidColorBrush(Colors.Red);
          }
       }
       protected override void OnDetaching()
       {
           base.OnDetaching();
           TextBox txtBox = AssociatedObject as TextBox;
           txtBox.TextChanged -= txt_TextChanged;
         
       }
   }
}

To attach this behavior with the Textbox, suppose we have a window TextChangeBhehaviourTest.xaml

<Window x:Class="WpfApplication1.TextChangeBhehaviourTest"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:TxtChBhe="clr-namespace:BehavoiurTest"
       xmlns:e="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
       Title="TextChangeBhehaviourTest" Height="300" Width="300">
   <Grid>
       <TextBox Width="150" Height="25">
           <e:Interaction.Behaviors>
               <TxtChBhe:TextChangeBehavior></TxtChBhe:TextChangeBehavior>
           </e:Interaction.Behaviors>
       </TextBox>
   </Grid>
</Window>

here we need to add assembly of Interactivity.