Using behaviors WPF/C#

LARABA MOHAMMED SEDDIK
1 min readFeb 22, 2019

In this small article, I shall demonstrate how to use WPF behavior to add features to UI Controls. All you need is to reference the official System.Windows.Interactivity library or download the NuGet package Expression.Blend.Sdk.

Think of behaviors as a piece of code that can do any customization to the UI control without touching the original UI control, it can also be injected on both c# code or XAML.

Behaviors have so many useful utilisations, like attaching popup on text boxes to add autocomplete features, inputs validation, styling, …

Let me demonstrate :

Step 1: creating the behavior

Behavior is simply a class inherited from Behavoir<> class, where the generic argument is the UI control type.

public class YellowifyBehavior : Behavior<TextBox>
{
protected override void OnAttached()
{
AssociatedObject.Background = Brushes.Yellow;
}
}

This is a simple behavior that set the background to yellow for Textboxes. Let me explain this piece of code :

OnAttached is the method called when we activate the behavior by attaching it to any Textbox we like.

AssociatedObject is the UI control (the Textbox in our example), that the behavior has been applied to.

So as soon as we attach the behavior to the Textbox it changes his the background.

The next step is to attach the behavior to a Textbox.

Step 2: Attaching the behavior

as mentioned before we can attach behavior to controls both ways:

Attach on the code :

Interaction.GetBehaviors(mytextbox).Add(new YellowifyBehavior());

Attach on XAML :

<TextBox>
<e:Interaction.Behaviors>
<local:YellowifyBehavior/>
</e:Interaction.Behaviors>
</TextBox>

--

--