[Behaviors] How to attach behavior in code behind (Silverlight 3)

For those of you who would like to add (attach) behavior to control in code behind, there is a simple solution.

Adding Behaviors

Let's say that we have xaml code like this one:

<TextBox x:Name="TextBoxInvoker" Text="TextBoxControl"  >

     <i:Interaction.Behaviors>

          <behavior:TextBoxSimpleBehavior />

     </i:Interaction.Behaviors>

</TextBox>

, where "i:" is a namespace for "clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" and "behavior:" is a namespace for behavior's class "TextBoxSimpleBehavior", which  can be simple class like this one (just adding typed letters to content):

using System;

using System.Net;

using System.Windows;

using System.Windows.Controls;

using System.Windows.Documents;

using System.Windows.Ink;

using System.Windows.Input;

using System.Windows.Media;

using System.Windows.Media.Animation;

using System.Windows.Shapes;

using System.Windows.Interactivity;

/// Dummy  sample behavior for TextBox control.

/// It add extra letter in the end of Text property.

///

/// Jacek Ciereszko

/// https://geekswithblogs.net/SilverBlog/

///

namespace TextBoxEnterBehavior

{

    public class TextBoxSimpleBehavior: Behavior<TextBox>

    {

        public TextBoxSimpleBehavior: base { }

        ///

        /// Called after the Behavior is attached to an AssociatedObject.

        ///

        /// Override this to hook up functionality to the AssociatedObject.

        protected override void OnAttached

        {

            base.OnAttached;

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

        }

        ///

        /// Called after the Behavior is detached from an AssociatedObject.

        ///

        /// Override this to hook up functionality to the AssociatedObject.

        protected override void OnDetaching

        {

            base.OnDetaching;

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

        }

        /// Simple operation on TextBox

        void AssociatedObject_KeyDown(object sender, KeyEventArgs e)

        {

            this.AssociatedObject.Text += e.Key;

        }

    }

}

So, to do the same operation in code behind, write:

// Adding behavior in code behind

TextBoxSimpleBehavior textBoxSimpleBehavior = new TextBoxSimpleBehavior;

            System.Windows.Interactivity.Interaction.GetBehaviors(TextBoxInvoker).Add(textBoxSimpleBehavior);

Adding Triggers

In this example I will use my TargetedTriggerAction from previous post https://geekswithblogs.net/SilverBlog/archive/2009/09/21/behaviors-textbox-enter-button-invoke-targetedtriggeraction.aspx In xaml I attached my TriggerAction using this code:

<Button x:Name="TargetedButton" Content="Targeted Button"  />

<TextBox x:Name="TextBoxInvoker" Text="TextBox" >

    <i:Interaction.Triggers>

        <i:EventTrigger EventName="KeyDown" >

            <behavior:TextBoxEnterButtonInvoke TargetName="TargetedButton" />

        </i:EventTrigger>

    </i:Interaction.Triggers>

</TextBox>

where "i:" is a namespace for "clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity" and "behavior:" is a namespace for behavior's code.

In code behind I will write this code:

// Adding TriggerAction in code behind

TextBoxEnterButtonInvoke textBoxEnterButtonInvoke = new TextBoxEnterButtonInvoke;

textBoxEnterButtonInvoke.TargetName = "TargetedButton";

System.Windows.Interactivity.EventTrigger eventTrigger = new System.Windows.Interactivity.EventTrigger("KeyDown");

eventTrigger.Actions.Add(textBoxEnterButtonInvoke);

System.Windows.Interactivity.Interaction.GetTriggers(TextBoxInvoker).Add(eventTrigger);

Done! That's all we need to attach behaviors in code behind.

--- Jacek Ciereszko

This article is part of the GWB Archives. Original Author: Jacek

New on Geeks with Blogs

  • We Won The One Award I Actually Care About

    Full Scale made the Inc. 5000 for the fifth year straight, the 12th listing across my three companies. Here is why the one award you cannot buy is worth stopping for.

  • Your Customers Build the Features Now

    I let a tool I liked sit dead for a year rather than build the features I wanted. An MCP server meant I never had to, and your customers can do the same to your product.

  • Get the Size of a Directory in Linux the Easy Way

    du -sh for the quick answer, ncdu for the cleanup, df for the disk itself: every command for checking directory size in Linux, plus why du and df never agree.

  • Vim Search and Replace: The Ultimate Guide

    One :%s command replaces every match in a file before a find dialog would even open. The Vim substitute patterns worth the muscle memory: flags, ranges, capture groups, and multi-file edits.