Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

Thanks!

like image 622
djcouchycouch Avatar asked Feb 03 '23 10:02

djcouchycouch


2 Answers

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.

like image 110
Charlie Avatar answered Feb 06 '23 04:02

Charlie


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;

using PropertyChanged;

[ImplementPropertyChanged]
public partial class Order
{
}

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.

like image 26
mark_h Avatar answered Feb 06 '23 04:02

mark_h