Sharing data between different ViewModels

后端 未结 6 2285
被撕碎了的回忆
被撕碎了的回忆 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-13 11:26

    In MVVM, models are the shared data store. I would persist the font size in the OptionsModel, which implements INotifyPropertyChanged. Any viewmodel interested in font size subscribes to PropertyChanged.

    class OptionsModel : BindableBase
    {
        public int FontSize {get; set;} // Assuming that BindableBase makes this setter invokes NotifyPropertyChanged
    }
    

    In the ViewModels that need to be updated when FontSize changes:

    internal void Initialize(OptionsModel model)
    {
        this.model = model;
        model.PropertyChanged += ModelPropertyChanged;
    
        // Initialize properties with data from the model
    }
    
    private void ModelPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
    {
        if (e.PropertyName == nameof(OptionsModel.FontSize))
        {
            // Update properties with data from the model
        }
    }
    

提交回复
热议问题