WPF Kaizen: Remora Pattern aka Attached Behavior
Once in a while every WPF developer would need to add extra behavior to one or more view elements.
For example we might be required to:
- Scroll an item of the list box into view based on some logic
- Auto select textbox text on it’s click event
In such scenarios we could write code-behind event handler but that it would not be the ideal solution if we use MVVM pattern.
As a workaround Ben Con suggested Remora Pattern which allows us to attach the behavioral logic to any view element – the logic is defined in a separate class and is hooked to the view element via attached-dependency property, any time the dependency property is set/unset the respective behavior logic is invoked.
Advantage of this pattern:
- behavior logic is well encapsulated in a separate class and is easy to maintain
- the behavior could be attached to one or more type of controls
- we could invoke/route/reuse commands
Check out Josh Smith’s article on attached behavior to learn more.