2

Currently I'm coding pretty much with WPF Applications in MVVM style. I want to extend my current BaseViewModel with some new stuff that makes things easier and faster. One functionality I want to add is to observe all properties (with a specific attribute) and call the PropertyChanged event when the property is changed by default. (This functionality is more about laziness, so it's not that important but I don't know how to accomplish this)

Currently I define a properties in the subclass like this:

private string _foo;
public string Foo
{
    get { return _foo; }
    set { _foo = value; OnPropertyChanged(); }
}

I plan to define (because it's faster and less code) the properties like this:

[Observe]
public string Foo { get; set; }

Is there any valid way to call the property changed event by default for every "marked" property in each sub class when the "set" method is called?

Thelonias
  • 2,918
  • 3
  • 29
  • 63
  • While it would be possible to do some fancy dynamic code generation, it more hassle then it's worth. I would suggest creating a snippet if writing the code is too tedious. – Titian Cernicova-Dragomir Nov 28 '17 at 15:40
  • I'm not sure why you would want to mark properties to notify later. you can notify right ahead. the solution most probably involves attributes and reflection which can be very slow at runtime. another workaround would be to update the `Model` of your `ViewModel` right when the property changes so that you can keep track of every change in data. – Bizhan Nov 28 '17 at 15:41
  • I would suggest to have a look at how MVVM light is doing this. Not with an annotation but they have a `Set` method that does all the checks and RaisePropertyChange if necessary. Example: http://www.mvvmlight.net/help/SL5/html/37ffba06-fd99-b7eb-f34e-5d7bfed60aca.htm – Fildor Nov 28 '17 at 15:42
  • BTW, if you are looking for a piece of reflection code for this, I would suggest you ask the question without mvvm and wpf tags – Bizhan Nov 28 '17 at 15:43
  • Possible duplicate of [Implementing INotifyPropertyChanged - does a better way exist?](https://stackoverflow.com/questions/1315621/implementing-inotifypropertychanged-does-a-better-way-exist) – ASh Nov 28 '17 at 15:48

1 Answers1

0

You probably want to take a look at Fody.

It injects INotifyPropertyChanged code into properties at compile time.

mm8
  • 163,881
  • 10
  • 57
  • 88
  • This actually looks pretty intresting. I ill try it out to see if Fody works for my purposes. If this does not work im gonna look for a visual studio code shortcut to fill in the code – Valentin Weiß Nov 28 '17 at 15:54