Sharing data between different ViewModels

2019-02-05 15: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 or BackgroundColor:

    <TextBlock FontSize="{Binding EditorFontSize}"></TextBlock>

its DataContext is MainWindowViewModel:

public class MainWindowViewModel : BindableBase
{     
    public int EditorFontSize
    {
        get { return _editorFontSize; }
        set { SetProperty(ref _editorFontSize, value); }
    } 
.....
  1. The second window is the option window, where I have an slider for changing the font size:

<Slider Maximum="30" Minimum="10" Value="{Binding EditorFontSize }" ></Slider>

its DataContext is OptionViewModel:

public class OptionViewModel: BindableBase
{     
    public int EditorFontSize
    {
        get { return _editorFontSize; }
        set { SetProperty(ref _editorFontSize, value); }
    }
.....

My problem is that I have to get the value of the slider in the option window and then I have to modify the FontSize property of my TextBlock with this value. But I don't know how to send the font size from OptionViewModel to MainViewModel.

I think that I should use:

  1. A shared model
  2. A model in MainWindowViewModel and a ref of this model in OptionViewModel
  3. Other systems like notifications, messages ...

I hope that you can help me. It's my first MVVM project and English isn't my main language :S

Thanks

回答1:

There are many ways to communicate between view models and a lot of points what the point is the best. You can see how it is done:

  • using MVVMLight

  • in Prism

  • by Caliburn

In my view, the best approach is using EventAggregator pattern of Prism framework. The Prism simplifies MVVM pattern. However, if you have not used Prism, you can use Rachel Lim's tutorial - simplified version of EventAggregator pattern by Rachel Lim.. I highly recommend you Rachel Lim's approach.

If you use Rachel Lim's tutorial, then you should create a common class:

public static class EventSystem
{...Here Publish and Subscribe methods to event...}

And publish an event into your OptionViewModel:

eventAggregator.GetEvent<ChangeStockEvent>().Publish(
new TickerSymbolSelectedMessage{ StockSymbol = “STOCK0” });

then you subscribe in constructor of another your MainViewModel to an event:

eventAggregator.GetEvent<ChangeStockEvent>().Subscribe(ShowNews);

public void ShowNews(TickerSymbolSelectedMessage msg)
{
   // Handle Event
}

The Rachel Lim's simplified approach is the best approach that I've ever seen. However, if you want to create a big application, then you should read this article by Magnus Montin and at CSharpcorner with an example.

Update: For versions of Prism later than 5 CompositePresentationEvent is depreciated and completely removed in version 6, so you will need to change it to PubSubEvent everything else can stay the same.



回答2:

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;
        }
    }       
}


回答3:

I have done a big MVVM application with WPF. I have a lot of windows and I had the same problem. My solution maybe isn't very elegant, but it works perfectly.

First solution: I have done one unique ViewModel, splitting it in various file using a partial class.

All these files start with:

namespace MyVMNameSpace
{
    public partial class MainWindowViewModel : DevExpress.Mvvm.ViewModelBase
    {
        ...
    }
}

I'm using DevExpress, but, looking your code you have to try:

namespace MyVMNameSpace
{
    public partial class MainWindowViewModel : BindableBase
    {
        ...
    }
}

Second solution: Anyway, I have also a couple of different ViewModel to manage some of these windows. In this case, if I have some variables to read from one ViewModel to another, I set these variables as static.

Example:

    public static event EventHandler ListCOMChanged;
    private static List<string> p_ListCOM;
    public static List<string> ListCOM
    {
        get { return p_ListCOM; }
        set 
        {
            p_ListCOM = value;
            if (ListCOMChanged != null)
                ListCOMChanged(null, EventArgs.Empty);
        }
    }

Maybe the second solution is simplier and still ok for your need.

I hope this is clear. Ask me more details, if you want.



回答4:

I'm not a MVVM pro myself, but what I've worked around with problems like this is, having a main class that has all other view models as properties, and setting this class as data context of all the windows, I don't know if its good or bad but for your case it seems enough.

For a more sophisticated solution see this

For the simpler one,

You can do something like this,

public class MainViewModel : BindableBase
{
    FirstViewModel firstViewModel;

    public FirstViewModel FirstViewModel
    {
        get
        {
            return firstViewModel;
        }

        set
        {
            firstViewModel = value;
        }
    }

    public SecondViewModel SecondViewModel
    {
        get
        {
            return secondViewModel;
        }
        set
        {
            secondViewModel = value;
        }
    }

    SecondViewModel secondViewModel;

    public MainViewModel()
    {
        firstViewModel = new FirstViewModel();
        secondViewModel = new SecondViewModel();
    }
}

now you have to make another constructor for your OptionWindow passing a view model.

 public SecondWindow(BindableBase viewModel)
    {
        InitializeComponent();
        this.DataContext = viewModel;
    }

this is to make sure that both windows work on the same instance of a view model.

Now, just wherever you're opening the second window use these two lines

var window = new SecondWindow((ViewModelBase)this.DataContext);
        window.Show();

now you're passing the First Window's view model to the Second window, so that they work on the same instance of the MainViewModel.

Everything is done, just you've to address to binding as

<TextBlock FontSize="{Binding FirstViewModel.EditorFontSize}"></TextBlock>
<TextBlock FontSize="{Binding SecondViewModel.EditorFontSize}"></TextBlock>

and no need to say that the data context of First window is MainViewModel



回答5:

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
    }
}


标签: c# wpf mvvm