Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...