1
votes

all!

In my main window I have a Grid with 2 columns. In column 0 is a usercontrol with settings, in column 1 is usercontrol with content. The goal is to reset usercontrol with content when settings are changed. What is the right "MVVM"-way to do it?

Both usercontrols are implemented in MVVM-way, having all business logic in ViewModels.

Say I have a CheckBox bound to a Property in the settings-usercontrol:

Settings.xaml

...
<CheckBox IsChecked="{Binding Path=MySettingNr1}">
...

In Settings_ViewModel.cs

...
public bool MySettingNr1 
{
  get 
  {
    return _model.SttNr1;
  }
  set 
  {
    if(_model.SttNr1 == value) return;
    _model.SttNr1 = value;
    OnPropertyChanged(nameof(MySettingNr1));
  }
}
...

How can I notify my content usercontrol if user clicks this checkbox?
Routed event would possibly not do, because both usercontrols are neighbours in the main window grid.
The only way I thought about was to fire an event in the usercontrol with settings, catch it in main windows and call a function of the usercontrol with content. Is there a way to make this call chain shorter?

Thanks in advance.

1
What changes do you want to make to the content? Make a change in the viewmodel and bind it to the content. All changes must be made at the viewmodel level, otherwise it is no longer mvvmMeysam Asadi
After settings change content view should reset and get empty, since creating the content is a long process and cannot be performed along with settings' changes. Can I bind in the content usercontrol to a property of settings usercontrol?firelex

1 Answers

2
votes

You could use a single shared view model for the window that both user controls bind to, i.e. they both inherit the DataContext of the parent window. This way they could communicate through the shared view model directly.

If you prefer to have two different view models, one for each user control, you could use an event aggregator or a messenger to send an event/message from one view model to antoher in a loosely coupled way.

Most MVVM libraries have implemented solutions for this. Prism uses an event aggregator and MvvmLight uses a messenger, for example.

Please refer to this blog post for more information about the concept.