MVVM in WPF - How to alert ViewModel of changes in Model… or should I?

前端 未结 11 718
离开以前
离开以前 2020-11-27 09:51

I am going through some MVVM articles, primarily this and this.

My specific question is: How do I communicate Model changes from the Model to the ViewModel?<

11条回答
  •  孤街浪徒
    2020-11-27 10:24

    Your choices:

    • Implement INotifyPropertyChanged
    • Events
    • POCO with Proxy manipulator

    As I see it, INotifyPropertyChanged is a fundamental part of .Net. i.e. its in System.dll. Implementing it in your "Model" is akin to implementing an event structure.

    If you want pure POCO, then you effectively have to manipulate your objects via proxies/services and then your ViewModel is notified of changes by listening to the proxy.

    Personally I just loosely implement INotifyPropertyChanged and then use FODY to do the dirty work for me. It looks and feels POCO.

    An example (using FODY to IL Weave the PropertyChanged raisers):

    public class NearlyPOCO: INotifyPropertyChanged
    {
         public string ValueA {get;set;}
         public string ValueB {get;set;}
    
         public event PropertyChangedEventHandler PropertyChanged;
    }
    

    then you can have your ViewModel listen to PropertyChanged for any changes; or property specific changes.

    The beauty of the INotifyPropertyChanged route, is you chain it up with an Extended ObservableCollection. So you dump your near poco objects into a collection, and listen to the collection... if anything changes, anywhere, you learn about it.

    I'll be honest, this could join the "Why wasn't INotifyPropertyChanged autmatically handled by the compiler" discussion, which devolves to: Every object in c# should have the facility to notify if any part of it was changed; i.e. implement INotifyPropertyChanged by default. But it doesn't and the best route, that requires the least amount of effort, is to use IL Weaving (specifically FODY).

提交回复
热议问题