I am discovering MVVM for the first time and am using Caliburn.Micro.
I can articulate my question with a real example:
In my View I have a combobox from which the user can select an available Comport. The selected item is bound to a property in the ViewModel.
In one of my Models I have a scanner class which will use the Comport that the user selected.
This means that the scanner class needs to know about changes to the Comport property in the ViewModel. The question is, what is the best way to implement this?
I have considered:
1: Set properties / call methods in the Scanner class directly from the ViewModel when there is a change:
public string SelectedPartScannerComPort
{
get { return _selectedPartScannerComPort; }
set
{
_selectedPartScannerComPort = value;
NotifyOfPropertyChange(() => SelectedPartScannerComPort);
OnSelectedPartScannerComPortChanged();
}
}
...
...
private void OnSelectedPartScannerComPortChanged()
{
Models.Equipment.PartScanner.SetupPort(SelectedPartScannerComPort);
}
This works but it means that the ViewModel has code in it which is specific to the operation of the Model.
2:
I believe the notifying property in the ViewModel is an event, so I should be able to subscribe to it from the Model.
shellViewModel.SelectedPartScanner.PropertyChanged += OnPartScannerPropertyChanged;
I haven't been able to try it as I am struggling to discover where the ShellViewModel is declared so that I can access its instance to subscribe to the events.
In any case, this would mean the Model needs to know about the View Model.
It seems like no matter what I will do, either the ViewModel needs to know about the Model or the Model needs to know about the ViewModel.
Is this acceptable practice? Are there better ways to go about this?
What I have tried:
I have tried directly setting properties / calling methods in the model from the viewmodel. It works but I am concerned that I am misunderstanding MVVM.