Sharing data between different ViewModels

后端 未结 6 2284
被撕碎了的回忆
被撕碎了的回忆 2020-12-13 11:08

I\'m trying to develop an easy MVVM project that it has two windows:

  1. The first window is a text editor, where I bind some properties such as FontSize

6条回答
  •  盖世英雄少女心
    2020-12-13 11:38

    Another option is to store such "shared" variables in a SessionContext-class of some kind:

    public interface ISessionContext: INotifyPropertyChanged 
    {
        int EditorFontSize { get;set; }
    }
    

    Then, inject this into your viewmodels (you are using Dependency Injection, right?) and register to the PropertyChanged event:

    public class MainWindowViewModel 
    {
        public MainWindowViewModel(ISessionContext sessionContext)
        {
            sessionContext.PropertyChanged += OnSessionContextPropertyChanged;        
        }
    
        private void OnSessionContextPropertyChanged(object sender, PropertyChangedEventArgs e) 
        {
            if (e.PropertyName == "EditorFontSize")
            {
                this.EditorFontSize = sessionContext.EditorFontSize;
            }
        }       
    }
    

提交回复
热议问题