Search code examples
c#wpfmvvminotifypropertychangedeventaggregator

When is it ok to combine 2 viewmodels into 1 instead of using some form of viewmodel-viewmodel communication?


I have 2 viewmodels that each have their own view.

the first view model has 3 properties being displayed by the view:

PolicyProvider

PolicyType

PolicyNumber

the second view model has only 1 property being displayed by its view:

TypeOfInvestmentFund

There is a 1 to many relationship between the PolicyType and the TypeOfInvestmentFund.

Both of these view models and their views are being displayed as user controls inside a parent form.

The available choices for the TypeOfInvestmentFund is dependent on which PolicyType is selected in the other view.


To me this feels like these 2 view models could be combined, because

a) they are clearly somewhat coupled

b) the controls are both so small and simple that joining them will not create a complex and unmanageable object.

However this data is fairly unrelated; unrelated enough that the user would still want the data visible in seperate parts of the form (and therefore be placed on seperate views).

I personally feel that combining these 2 view models and having 2 seperate views connect to it to display different parts of it is a lot less overhead then managing the communication between the 2 objects.

I could however create loosely coupled events with the Prism Event Aggregator, and although I have never done this it is probably not much to manage, and keeping these 2 view models seperate would preserve seperation of concerns. Furthermore if other controls were to appear later on in development that also need this information, I cant keep absorbing them, so starting an event aggregator at this stage would prevent rework as the events would be available already to subscribe to. It is still more work then just combining the view models.

Which one of these 2 is 'more correct'? I understand its a judgement call, but I can't decide so I'm looking for opinions to help me make up my mind.


Solution

  • Ok thank you for the replies. Got a bunch of ideas from Rachels suggestion (upvote for you ma'am) but none of them paned out. In the end the project manager didn't like the idea and wants me to implement a more standard approach for readability and to prevent rework, so I'm going to go the message root.

    Instead of eventaggregator I'm just going to make the parent subscribe to the PropertyChanged event of the Policy child and then change a property of the TypeOfInvestment child.

    I'm kinda bummed I didnt get to implement the viewmodel merge as it really made more sense to me.