MVVM – Child Windows and Data Contexts in MVVM

mvvm

Should a child window have it's own data context (View-Model) or use the data context of the parent? More broadly, should each View have its own View-Model? Are there are any rules to guide making that decision? What if the various View-Models will be accessing the same Model?

I haven't been able to find any consistent guidance on my question. The MS definition of MVVM appears to be silent on child windows.

For one example, I have created a warning message notification View. It really didn't need a data context since it was passed the message to display. But if I needed to fancy it up a bit, I would have tapped the parent's data context.

I have run into another scenario that needs a child window and is more complicated than the notification box. The parent's View-Model is already getting cluttered, so I had planned on generating a dedicated VM for the child window. But I can't find any guidance on whether this is a good idea or what the potential consequences may be.

FWIW, I happen to be working in Silverlight, but I don't know that this question is strictly a Silverlight issue.

Best Answer

I guess it depends. On the project I am currently working on, we have used both approaches. I suppose it comes down to how related the child window's functionality is to the parent. If the new window is mostly supplemental, such as a prompt or minor input dialog, I have simply used the parent's data context because the data being provided through that dialog was still very relevant to the parent's functionality. On the other hand, if the new window is a significant feature in itself, it may be more appropriate to use a new data context that reports back to the parent (if applicable). Think of it this way, when designing a class, when is it appropriate to break out functionality into another class? You don't necessarily want an unwieldy view-model with a bunch of unrelated functionality lumped together.
Unfortunately, this has turned into a pretty fuzzy answer that depends on your best judgment.