Click here to Skip to main content
Click here to Skip to main content

Introduction to Attached Behaviors in WPF

, 30 Aug 2008 CPOL
Rate this:
Please Sign up or sign in to vote.
Explains the concept of attached behaviors and shows how to use them in the context of the MVVM pattern.



This article explains what an attached behavior is, and how you can implement them in a WPF application. Readers of this article should be somewhat familiar with WPF, XAML, attached properties, and the Model-View-ViewModel (MVVM) pattern. I highly recommend that you also read my ‘Simplifying the WPF TreeView by Using the ViewModel Pattern’ article, because the material here is an extension of the material presented in it.


Back in May of 2008, I published an article called ‘Simplifying the WPF TreeView by Using the ViewModel Pattern’. That article focused on the MVVM pattern. This morning, I woke up to find that a fellow by the name of Pascal Binggeli had asked an excellent question on that article’s message board.

Pascal wanted to know how to scroll a TreeViewItem into the viewable area of the TreeView control when its associated ViewModel object selects it. That seems simple enough, but upon further examination, it is not quite as straightforward as one might initially expect. The objective, and problem, is to find the proper place to put code that calls BringIntoView() on the selected TreeViewItem, such that the principles of the MVVM pattern are not violated.

For example, suppose that the user searches through a TreeView for an item whose display text matches a user-defined search string. When the search logic finds a matching item, the matching ViewModel object will have its IsSelected property set to true. Then, via the magic of data binding, the TreeViewItem associated with that ViewModel object enters into the selected state (i.e., its IsSelected property is set to true, too). However, that TreeViewItem will not necessarily be in view, which means the user will not see the item that matches their search string. Pascal wanted a TreeViewItem brought into view when the ViewModel determines that it is in the selected state.

The ViewModel objects have no idea that a TreeViewItem exists, and is bound to them, so it does not make sense to expect the ViewModel objects to bring TreeViewItems into view. The question becomes, now, who is responsible for bringing a TreeViewItem into view when the ViewModel forces it to be selected?

We certainly do not want to put that code into the ViewModel because it introduces an artificial, and unnecessary, coupling between a ViewModel object and a visual element. We do not want to put that code in the code-behind of every place a TreeView is bound to a ViewModel, because it reintroduces some of the problems that we avoid by using a ViewModel in the first place. We could create a TreeViewItem subclass that has built-in support for bringing itself into view when selected, but, in the WPF world, that is definitely a heavy-handed solution to a lightweight problem.

How can we elegantly solve this problem in a lightweight and reusable way?

Attached Behaviors

The solution to the problem explained above is to use an attached behavior. Attaching a behavior to an object simply means making the object do something that it would not do on its own. Here is the explanation of attached behaviors that I wrote in my ‘Working with CheckBoxes in the WPF TreeView’ article:

The idea is that you set an attached property on an element so that you can gain access to the element from the class that exposes the attached property. Once that class has access to the element, it can hook events on it and, in response to those events firing, make the element do things that it normally would not do. It is a very convenient alternative to creating and using subclasses, and is very XAML-friendly.

In that article, the demo application uses attached behaviors in complicated ways, but in this article, we will keep it simple. Enough with the background and theory, let’s see how to create an attached behavior that solves the problem posed by our friend Pascal.


This article’s demo app, which is available for download at the top of this page, uses the Text Search demo provided by the ‘Simplifying the WPF TreeView by Using the ViewModel Pattern’ article. I made a few changes, such as adding more items to the TreeView, increasing the font size, and adding an attached behavior. The attached behavior is in a new static class called TreeViewItemBehavior. That class exposes a Boolean attached property that can be set on a TreeViewItem, called IsBroughtIntoViewWhenSelected. Here is the TreeViewItemBehavior class:

/// <summary>
/// Exposes attached behaviors that can be
/// applied to TreeViewItem objects.
/// </summary>
public static class TreeViewItemBehavior
    #region IsBroughtIntoViewWhenSelected

    public static bool GetIsBroughtIntoViewWhenSelected(TreeViewItem treeViewItem)
        return (bool)treeViewItem.GetValue(IsBroughtIntoViewWhenSelectedProperty);

    public static void SetIsBroughtIntoViewWhenSelected(
      TreeViewItem treeViewItem, bool value)
        treeViewItem.SetValue(IsBroughtIntoViewWhenSelectedProperty, value);

    public static readonly DependencyProperty IsBroughtIntoViewWhenSelectedProperty =
        new UIPropertyMetadata(false, OnIsBroughtIntoViewWhenSelectedChanged));

    static void OnIsBroughtIntoViewWhenSelectedChanged(
      DependencyObject depObj, DependencyPropertyChangedEventArgs e)
        TreeViewItem item = depObj as TreeViewItem;
        if (item == null)

        if (e.NewValue is bool == false)

        if ((bool)e.NewValue)
            item.Selected += OnTreeViewItemSelected;
            item.Selected -= OnTreeViewItemSelected;

    static void OnTreeViewItemSelected(object sender, RoutedEventArgs e)
        // Only react to the Selected event raised by the TreeViewItem
        // whose IsSelected property was modified. Ignore all ancestors
        // who are merely reporting that a descendant's Selected fired.
        if (!Object.ReferenceEquals(sender, e.OriginalSource))

        TreeViewItem item = e.OriginalSource as TreeViewItem;
        if (item != null)

    #endregion // IsBroughtIntoViewWhenSelected

The attached behavior seen above is basically just a fancy way of hooking the Selected property of a TreeViewItem and, when the event is raised, calling BringIntoView() on the item. The final piece of this puzzle is seeing how the TreeViewItemBehavior class gets a reference to every TreeViewItem in the TreeView. We accomplish that by adding a Setter to the Style applied to every item in the TreeView, as seen below:

  <Style TargetType="{x:Type TreeViewItem}">
    This Setter applies an attached behavior to all TreeViewItems.

    These Setters bind a TreeViewItem to a PersonViewModel.
    <Setter Property="IsExpanded" Value="{Binding IsExpanded, Mode=TwoWay}" />
    <Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
    <Setter Property="FontWeight" Value="Normal" />
      <Trigger Property="IsSelected" Value="True">
        <Setter Property="FontWeight" Value="Bold" />

When the demo application loads up, the search text will be set to the letter Y automatically. Click the Find button a few times, and you will see that each time an item is selected, it will contain the letter Y and will scroll into view. The fact that it scrolls into view upon being selected means that the attached behavior is working properly.


Hooking an event on an object and doing something when it fires is certainly not a breakthrough innovation, by any stretch of the imagination. In that sense, attached behaviors are just another way to do the same old thing. However, the importance of this technique is that it has a name, which is probably the most important aspect of any design pattern. In addition, you can create attached behaviors and apply them to any element without having to modify any other part of the system. It is a clean solution to the problem raised by Pascal Binggeli, and many, many other problems. It's a very useful tool to have in your toolbox.


Revision History

  • August 30, 2008 – Created the article.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Josh Smith
Software Developer (Senior) Cynergy Systems
United States United States
Josh creates software, for iOS and Windows.
He works at Cynergy Systems as a Senior Experience Developer.
Read his iOS Programming for .NET Developers[^] book to learn how to write iPhone and iPad apps by leveraging your existing .NET skills.
Use his Master WPF[^] app on your iPhone to sharpen your WPF skills on the go.
Check out his Advanced MVVM[^] book.
Visit his WPF blog[^] or stop by his iOS blog[^].
Follow on   Twitter

Comments and Discussions

GeneralVery good article - thank you. PinmemberGil.Y13-Jan-15 11:34 
GeneralExcellent! Pinmemberhausl27-Oct-13 3:46 
QuestionCan not finde the type (to be continued) Pinmemberly_he17-Sep-13 2:30 
QuestionCan not find the type Pinmemberly_he16-Sep-13 23:59 
AnswerRe: Can not find the type Pinmemberleiyangge21-Apr-14 6:45 
GeneralRe: Can not find the type Pinmemberly_he6-Jun-14 7:23 
GeneralRe: Can not find the type Pinmemberleiyangge6-Jun-14 17:57 
GeneralRe: Can not find the type Pinmemberly_he19-Jun-14 22:41 
GeneralMy vote of 5 PinmemberVincent0269-Sep-13 21:23 
QuestionScratches head PinmemberMalicious Demon19-Jun-13 23:51 
GeneralMy vote of 5 PinmemberAvi Farah16-Jun-13 12:53 
QuestionRouted events using MVVM Pinmemberswapnil088331-May-13 2:48 
GeneralBrilliant! PinmemberMember 96564499-Jan-13 9:50 
QuestionSame article for Win Forms Pinmemberwout de zeeuw6-Dec-12 5:26 
GeneralMy vote of 5 PinmemberIonegative17-Oct-12 4:07 
QuestionApplied to a ListBox PinmemberKingKnecht18-Aug-12 12:25 
I have transferred this pattern of attached behavior to a ListBox and ran into following problems:
1. I have to scroll down once the ListBox until the ListBox item I'm searching gets visible. Otherwise ListBoxItem.BringIntoView() is not able to "jump". I think this is a problem of the virtualization of the ListBox. I think I could build my own template and use a "normal" StackPanel to get rid of the virtualization. But I don't want that. Is there a another solution for this?
2. If the item is already selected and I scroll away from the item then "jumping" isn't possible, because the mechanism of this behavior depends on changing the selection.Is there a solution for this?
3. I guess when apply this pattern to a TreeView I will have the same problems, right?
Questionawesome Pinmemberfujiwara113-Aug-12 9:55 
SuggestionNice explanation - maybe I have an alternative? PinmemberTorsten Tiedt10-Dec-11 7:48 
QuestionSelected event firing twice on each selection PinmemberJon Burchel30-Nov-11 20:47 
QuestionExcellent article. Need to mention virtualizing stack panel PinmemberBenjamin Tong4-Oct-11 7:51 
QuestionSelectedItemChanging or PreviewSelectedItem on Treeview in WPF... PinmemberLalit Krishna6-Sep-11 9:43 
GeneralMy vote of 5 PinmemberAshley Davis10-Mar-11 0:52 
GeneralMy vote of 5 PinmemberPranavpk5-Jan-11 1:04 
GeneralFucntion Not Used Pinmemberseabascuit14-Jul-10 18:49 
QuestionHow to keep out DependencyProperty plumbing Pinmemberloukach21-Feb-10 11:47 
AnswerRe: How to keep out DependencyProperty plumbing PinmvpJosh Smith22-Feb-10 6:07 
QuestionCan attached behavior bind to an instance method not only static method? Pinmemberstg60921-Feb-10 7:47 
AnswerRe: Can attached behavior bind to an instance method not only static method? PinmvpJosh Smith22-Feb-10 6:05 
GeneralGetting the selecteditem PinmemberNickB22-Jan-10 6:36 
GeneralRe: Getting the selecteditem PinmvpJosh Smith22-Jan-10 6:41 
GeneralRe: Getting the selecteditem PinmemberNickB22-Jan-10 6:49 
GeneralRe: Getting the selecteditem PinmemberNickB25-Jan-10 6:10 
GeneralRe: Getting the selecteditem PinmvpJosh Smith25-Jan-10 6:23 
Generalsolving similar problem with event handler PinmemberKitWest_dev8-Jan-10 10:34 
QuestionWhat if i want to access data from the view model? Pinmembersmellybob4321-Dec-09 0:47 
QuestionWhat about associating the attached behavior with non native events PinmemberDan dot Net1-Sep-09 6:44 
AnswerRe: What about associating the attached behavior with non native events PinmemberDan dot Net2-Sep-09 3:57 
GeneralRe: What about associating the attached behavior with non native events PinmvpJosh Smith2-Sep-09 6:24 
QuestionExcellent article! Pinmembershiroica12-Mar-09 8:43 
AnswerRe: Excellent article! PinmvpJosh Smith12-Mar-09 8:44 
GeneralRe: Excellent article! Pinmembershiroica13-Mar-09 2:51 
QuestionBinding KeyDown PinmemberVivekShri25-Jan-09 19:46 
AnswerRe: Binding KeyDown PinmvpJosh Smith28-Jan-09 11:50 
GeneralRe: Binding KeyDown PinmemberVivekShri29-Jan-09 6:49 
GeneralError in VB implementation PinmemberMolon Labe15-Nov-08 19:51 
GeneralRe: Error in VB implementation PinmemberMolon Labe15-Nov-08 21:30 
QuestionViewModel Factory ? Pinmemberquicoli3-Oct-08 2:30 
AnswerRe: ViewModel Factory ? PinmvpJosh Smith3-Oct-08 5:31 
GeneralIt's fine, but not work with virtualization Pinmemberivchpavel24-Sep-08 11:36 
GeneralRe: It's fine, but not work with virtualization PinmvpJosh Smith26-Sep-08 7:21 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.150327.1 | Last Updated 30 Aug 2008
Article Copyright 2008 by Josh Smith
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid