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?
Thanks!
I found that I was writing a lot of code to implement change notification via the INotifyPropertyChanged interface. To reduce this I found a NuGet package called PropertyChanged.Fody that makes adding INotifyPropertyChanged to a classes properties really simple.
Here's how to use it;
Now any public property in the class will have property changed notification. This is particularly useful for EF classes generated through DB first where you don't have total control over your entities.
See GitHub for more information.
Personally, I like Josh Smith's MVVM Foundation library. He uses a class called
RelayCommand
there, but it sounds pretty similar to yourDelegateCommand
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.
The most obvious strategy I can think of is using code snippets and/or file templates. It does not reduce the lines of codes but at least it makes you save time.
You can make them yourself(or find some you can import directly to your Visual studio).
I personally use the mvvm light toolkit from Laurent Bugnion and I use his code-snippets/file templates, they do save me a lot of time. I would assume there is something similar for most of the popular mvvm toolkits.
Hope it helps!