Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
165 views
in Technique[技术] by (71.8m points)

c# - Sharing data between different ViewModels

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...