Attached behaviors
Attached behaviors are generally used to cause some code to be executed on the view based on some property changes in the view model. They are phenomenal for this purpose. They are also used to tackle non-MVVM features of otherwise MVVM-based controls. For example, when using Window
in WPF how can a view model cause it's associated window to be close? The only way to close a window is to directly call the
Window.Close()
method on the instance. Since we don't want our view models to hold references to our views, our view models cannot call Close()
method directly. Window
also does not have any DependencyProperty
that could be bound to a view model property to allow for closing the window. One way to resolve this problem is using an attached behavior. Using this pattern, our view model sets a notification-based property and rest is taken care of by using the attached behavior approach shown next. For this technique, we need to use INotifyPropertyChanged
, Data Triggers
...