0

I have a view that I'll call View1 that has a nested user control that I'll call View2. My main application creates and shows View1 which in turn creates View2 since it is a user control on View1. Both View1 and View2 have their own viewmodels. What I need to do is get a value from View1's viewmodel to View2's viewmodel.

View2 is meant to be a completely self-contained control with its own functionality that is reusable in any other view, but it needs a piece of information from whatever view it is contained in. In the case given here, that would be View1.

My first attempt was to create a dependency property on View2 so it could be set in View1 like so:

<myUserControls:View2 MyProperty="{Binding RelativeSource={RelativeSource Self}, Path=Parent.DataContext.MyProperty}"/>

This works to set the dependency property, but that doesn't help to get the property value into View2's viewmodel where I can work with it.

I am doing this in Silverlight, if that makes any difference.

Anyone know if there is a way to do this?

meyousikmann
  • 163
  • 4
  • 14
  • Communication between VMs can be done safely using *Mediator pattern*, see [discussion in this answer](http://stackoverflow.com/a/21332502/2998271) – har07 Sep 19 '14 at 05:58

1 Answers1

0

I would recommend using the "Mediator" pattern, or some sort of communication between viewmodels. I personally have used galasoft MVVM light messaging to great deals of success. Rachel has also written a pretty good blog on navigation: Rachel's MVVM blog

But I would try and decrease the coupling in your program by letting the messaging handle the data context switch and viewmodel updates as opposed to creating a dependency property.

You could for instance have a baseviewmodel class which all view models inherit from, and use a polymorphic generic "view model" property which is of type baseviewmodel in your main viewmodel. Once the message was received to switch from viewmodel #1 to viewmodel #2, call a "update model" function (which you have declared in your baseviewmodel and override in your VM #2) which will then handle updating your VM #2.

Stunna
  • 413
  • 6
  • 16
  • You could also stuff a generic "data object" into your message so that when VM #1 sends the message, it also sends the value you need for VM #2. – Stunna Sep 19 '14 at 18:26