djcouchycouch djcouchycouch - 9 months ago 76
C# Question

Reducing boilerplate code in MVVM WPF app for attached properties, commands, etc?

I'm working on a WPF MVVM application. The thing that I'm noticing is that I have to write an inordinate amount of boilerplate code just to declare commands (through DelegateCommands from the WPF Team's MVVM Toolkit), attached properties and attached behaviors. Are there any strategies available to reduce the amount of boilerplate code I have to write?


Answer Source

Personally, I like Josh Smith's MVVM Foundation library. He uses a class called RelayCommand there, but it sounds pretty similar to your DelegateCommand from the toolkit. It lets you create a command and pass the CanExecute and Execute logic through lambda expressions. That will help reduce a lot of boilerplate code.

In his blog, Josh also talks about using a generic property observer to avoid some of the messier aspects of PropertyChanged event handling. That is worth looking into, as well.

Honestly though, a lot of the so-called "boilerplate" code is setting up a very dynamic and flexible foundation for your application. If you are making a small, easily maintained application, you might ask yourself, "do I even need to apply the MVVM pattern here?" If, on the other hand, you are making a larger application that will have a long life-time and require a lot of maintenance, then this boilerplate code is going to save you down the line.