Attached Behaviors & MVVM

When you think of MVVM and other patterns involved, it is often about separation of concerns as much as possible, unit testability and code maintainability. These type of patterns help in high quality of code and efficient development of business functionality. If you are new to MVVM then you may want to check out some of the articles by various intellects like Josh Smith, Laurent Bugnion and few others from XAML Disciples group(or just Google Smile).

There are lot many frameworks on MVVM out there and to be frank there isn’t any right or the wrong one. You need to evaluate and decide on the one that fits your need! Most often people land up writing one on their own and in a way it is good!

I personally like a framework written by Brette Esterbrooks because it is a skeleton of code that you need and helps you get started. I tweaked it a bit(basically removed the ones that I don’t need) and thus the sample attached on this blog will have a tiny little framework of MVVM.

All it has is just a few helper classes:

  1. ViewBase,
  2. ViewModelBase,
  3. RelayCommand,
  4. ObservableObject.

Attached Behaviors


Attached behavior is achieved by simply attaching a behavior to a control that otherwise wouldn’t have anything of its own.

And as per Josh Smith-

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.

Ever since I am hooked to MVVM pattern, I try and avoid all the code that usually goes to the code behind. For e.g. a click event handler usually written in the code behind can be omitted and a RelayCommand in the ViewModel be used instead.

But what would happen if you want to handle a double click or a focus event of a control? Just retaining those kind of events to the code behind defeats the pattern itself. And thus Attached Behavior comes to rescue! Demo included in this post explains the DragDropBehavior.

Before you go further with this approach, I just want you to know that you can achieve this by Behavior<T> class included in the However this dll is available only through Expression Blend installation.

In my demo I have explained both of the implementation and it’s usage. Here we go!

Screenshot of the Demo:






The view models can hold the reference of this contract and change at runtime if needed:

  1. public interface IBehavior
  2.     {
  3.         void OnEnabled(DependencyObject dependencyObject);
  4.         void OnDisabling(DependencyObject dependencyObject);
  5.     }



AttachedBehavior – A static class!


A static class AttachedBehavior is introduced which holds the attached properties “Behavior” and “IsEnabled”.

When toggled from Enabled state to Disabled State – OnDisabling() method of the IBehavior is called. Use this method to unwire your event handlers.


  1. /// <summary>
  2.         /// Attach a Behavior of type IBehavior
  3.         /// </summary>
  4.         public static readonly DependencyProperty BehaviorProperty = DependencyProperty.RegisterAttached("Behavior", typeof(IBehavior), typeof(AttachedBehavior), new UIPropertyMetadata(null));
  6.         /// <summary>
  7.         /// Is Enabled, when set to true, fires Behaviors OnEnabled Method
  8.         /// </summary>
  9.         public static readonly DependencyProperty IsEnabledProperty = DependencyProperty.RegisterAttached("IsEnabled", typeof(bool), typeof(AttachedBehavior), new UIPropertyMetadata(false, OnIsEnabledChanged));
  11.         /// <summary>
  12.         /// Handles IsEnabledChanged
  13.         /// </summary>
  14.         /// <param name="d"></param>
  15.         /// <param name="e"></param>
  16.         private static void OnIsEnabledChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
  17.         {
  18.             if (d == null)
  19.                 return;
  20.             var behavior = GetBehavior(d);
  21.             if (behavior == null)
  22.                 return;
  23.             if ((bool)e.NewValue)
  24.                 behavior.OnEnabled(d);
  25.             else
  26.                 behavior.OnDisabling(d);
  27.         }


DragDropBehavior Class


DragDropBehavior class implements the IBehavior. Have a look at the OnEnabled and OnDisabling methods.

  1. public class DragDropBehavior : IBehavior
  2.     {
  3.         #region Private Fields
  4.         private Point _startPosition;
  5.         private Point _mouseStartPosition;
  6.         private TranslateTransform _translatetransform;
  7.         private UIElement _associatedObject = null;
  8.         private Window _parent = null;
  9.         #endregion
  11.         #region IBehavior Members
  12.         public void OnEnabled(DependencyObject dependencyObject)
  13.         {
  14.             var uiElement = dependencyObject as UIElement;
  15.             if (uiElement == null)
  16.                 return;
  18.             _associatedObject = uiElement;
  19.             //TODO: set the parent accordingly
  20.              _parent = Application.Current.MainWindow;
  21.             _translatetransform = new TranslateTransform();
  22.             _associatedObject.RenderTransform = _translatetransform;
  23.             _associatedObject.MouseLeftButtonDown += AssociatedObjectMouseLeftButtonDown;
  24.             _associatedObject.MouseLeftButtonUp += AssociatedObjectMouseLeftButtonUp;
  25.             _associatedObject.MouseMove += AssociatedObjectMouseMove;
  26.         }
  28.         public void OnDisabling(DependencyObject dependencyObject)
  29.         {
  30.             _associatedObject.MouseLeftButtonDown -= AssociatedObjectMouseLeftButtonDown;
  31.             _associatedObject.MouseLeftButtonUp -= AssociatedObjectMouseLeftButtonUp;
  32.             _associatedObject.MouseMove -= AssociatedObjectMouseMove;
  33.             _translatetransform = null;
  34.         }
  35.         #endregion
  37.         #region Event Handlers
  38.         void AssociatedObjectMouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
  39.         {
  40.             _startPosition = _associatedObject.TranslatePoint(new Point(), _parent);
  41.             _mouseStartPosition = e.GetPosition(_parent);
  42.             _associatedObject.CaptureMouse();
  43.         }
  45.         void AssociatedObjectMouseMove(object sender, System.Windows.Input.MouseEventArgs e)
  46.         {
  47.             var positionDifference = e.GetPosition(_parent) – _mouseStartPosition;
  48.             if(_associatedObject.IsMouseCaptured)
  49.             {
  50.                 _translatetransform.X = positionDifference.X;
  51.                 _translatetransform.Y = positionDifference.Y;
  52.             }
  53.         }
  55.         void AssociatedObjectMouseLeftButtonUp(object sender, System.Windows.Input.MouseButtonEventArgs e)
  56.         {
  57.             _associatedObject.ReleaseMouseCapture();
  59.         }
  61.         #endregion
  64.     }




Attach is the behavior to the control that you want to drag:

  1. <ToggleButton Name="dragDropToggleButton" Command="{Binding ToggleDragDropBehavior}" Width="200">
  2.                 <ToggleButton.Style>
  3.                     <Style TargetType="{x:Type ToggleButton}">
  4.                         <Setter Property="Content" Value="Start Dragging"/>
  5.                         <Style.Triggers>
  6.                             <Trigger Property="IsChecked" Value="True">
  7.                                 <Setter Property="Content" Value="Stop Dragging"/>
  8.                             </Trigger>
  9.                         </Style.Triggers>
  10.                     </Style>
  11.                 </ToggleButton.Style>
  12.             </ToggleButton>
  16.               <TextBlock Background="Gold"
  17.                        Text="dragMe using attached behavior"
  18.                        Behaviors:AttachedBehavior.IsEnabled="{Binding IsDragBehaviorEnabled}"
  19.                        Behaviors:AttachedBehavior.Behavior="{Binding DragDropBehavior}"
  20.                        Canvas.Left="32"
  21.                        Canvas.Top="31" />




And finally the ViewModel that set’s the DragDropBehavior:

  1. public class HelloViewViewModel : ViewModelBase
  2.     {
  3.         private IBehavior _dragDropBehavior;
  4.         private bool _isDragBehaviorEnabled;
  6.         public bool IsDragBehaviorEnabled
  7.         {
  8.             get { return _isDragBehaviorEnabled; }
  9.             set { _isDragBehaviorEnabled = value; RaisePropertyChanged(()=> this.IsDragBehaviorEnabled); }
  10.         }
  12.         public IBehavior DragDropBehavior
  13.         {
  14.             get { return _dragDropBehavior; }
  15.             set { _dragDropBehavior = value; RaisePropertyChanged(() => this.DragDropBehavior); }
  16.         }
  18.         public RelayCommand ToggleDragDropBehavior { get; set; }
  20.         public HelloViewViewModel()
  21.         {
  22.             DragDropBehavior = new DragDropBehavior();
  23.             ToggleDragDropBehavior = new RelayCommand(() =>
  24.             {
  25.                 IsDragBehaviorEnabled = !IsDragBehaviorEnabled;
  26.             });
  28.         }
  29.     }


That’s It – you are done!! Refer DragDropBehavior2 class for implementation using Behavior<T>.

Download the Code – Read the Disclaimer of this blog before you work with this code!


7 thoughts on “Attached Behaviors & MVVM

  1. Hi ,
    I went through josh smith’s article on attached behavior

    He has similar implementation without a Behavior class .
    Is there any specific advantage u see if one implement using Behavior class .

    I think Josh’s solution will too work for drag and drop..

    Also he uses static class and we can attach the property directly in xaml without instantiating it in viewmodel.

    Let me know ur comments on it.


  2. Hi Satyajit, If you look at my example I have implementation in both (one without the Behavior as well). Behavior is in present in and this dll is available only through Expression Blend installation. I don’t see any specific advantage using Behavior class except that you have a neater code.

    1. This could be because your network is not allowing the access to DropBox. If you are connecting to this from your corporate network, can you try outside – may be from home and see if it works!

      I was able to access them.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.