Change Notification in MVVM Hierarchies

前端 未结 5 1337
清酒与你
清酒与你 2021-02-01 07:29

Let\'s say in some abstract ViewModel base-class I have a plain-old property as follows:

public Size Size
{
    get { return _size; }
    set
    {
        _size         


        
5条回答
  •  误落风尘
    2021-02-01 08:14

    A clean MVVM way would be to use a Messenger subscribe/notify mechanism (like in Josh Smith's MvvmFoundation)

    Create a singleton Messenger object somewhere - the main App class is always a good place for this

    public partial class App : Application
    {
        private static Messenger _messenger;
        public static Messenger Messenger
        {
            get
            {
                if (_messenger == null)
                {
                    _messenger = new Messenger();
                }
                return _messenger;
            }
        }
    }
    

    In the Size setter from the base class, notify changes:

    public Size Size
    {
        get { return _size; }
        set
        {
            _size = value;
            OnPropertyChanged("Size");
    
            App.Messenger.NotifyColleagues("SIZE_CHANGED");
        }
    }
    

    Now you can let your inherited ViewModel's listen for these changes, and raise PropertyChanged events as appropriate...

    public MyViewModel : MyViewModelBase
    {
        public MyViewModel()
        {
            App.Messenger.Register("SIZE_CHANGED", () => OnPropertyChanged("Rectangle"));
        }
    }
    

    Of course - you can add as many subscriptions to this message as you need - one for each property that needs changes to be notified back to the View...

    Hope this helps :)

提交回复
热议问题