Reputation: 43
I am new to the MVVM pattern, and not sure how to handle communication between view models. There is a table view that contains multiple cell views. I created view models for the table and each cell:
TableView - TableViewModel
InputCellView - InputCellViewModel
CheckboxCellView - CheckboxCellViewModel
.....
The cells contains user input elements like text fields, checkboxes and so on. Each CellViewModel holds the data that was input by the user in the corresponding cell. My question is, what is the best way to transfer that data to the TableViewModel? I am currently thinking of passing a reference of TableViewModel the every CellViewModel and whenever the user changes some data in a cell, the CellViewModel will forward it to the TableViewModel. Is this a valid aproach with the MVVM pattern? Or is it better to user some kind of event system to notify the TableViewModel about changes in a CellViewModel?
Upvotes: 4
Views: 1683
Reputation: 133
You can use prism EventAggregator. It is a very Simple way. I pass empty string but you can pass any parameters
public class Exit : PubSubEvent<object> {}
public class FirstVM{
private readonly IEventAggregator eventAggregator;
public FirstVM(IEventAggregator eventAggregator)
{
this.eventAggregator = eventAggregator;
this.eventAggregator.GetEvent<Exit >().Subscribe(s => { DoWhatYoNeed.. });
}
}
public class SecondVM{ private void SendEvent()
{
...
this.eventAggregator.GetEvent<Exit>().Publish(string.Empty);
}}
Upvotes: 0
Reputation: 10883
I wouldn't pass the data from the CellViewModel
to the TableViewModel
, I would pass it directly to the Table
(-Model
). The update in the Table
then triggers an update of the TableViewModel
.
Remember: the view models prepare data for the view to consume, and they perform updates on the data on behalf of the view (read: the user), but they don't own the data.
The table data doesn't belong to the TableViewModel
, so no one needs to ask the TableViewModel
for permission to change the data, and the TableViewModel
is responsible for showing the correct and current data.
so...
Or is it better to user some kind of event system to notify the TableViewModel about changes in a CellViewModel?
Yes, that's preferred. But be aware that there aren't any changes in the CellViewModel
, there are changes forwarded by the CellViewModel
...
Upvotes: 1