Reputation: 296
In my ViewmodelA
I want to open a new window in ViewModelB
, so i used the messenger class, but the probleme is that i need to reference ViewModelB
inside the ViewModelA
, so that ViewModelB
can listen to the messages.
here is my implementation
in ViewModelA:
private void btnAddExecute()
{
// I need to instanciate ViewModelB otherwise it wont work/listen
ViewModelB vb= new ViewModelB();
Messenger.Default.Send(new NotificationMessage("ShowWindow"));
}
in ViewModelB
i listen to the broadcasted messages in it's constructor.
is there anyway to decouple ViewmodelA
from ViewmodelB
?
Upvotes: 2
Views: 1661
Reputation: 3120
I don't exactly see where the coupling is occurring if you are using the messenger properly. There is no need to reference ViewModelB
Edit
Here is a way to do it without reference to an instance ViewModelB
. It uses a singleton to register for messages and create ViewModelB
s when it receives the notification message. I haven't tested this, it is just an idea. Make sure ViewModelBCreator is used at some point so that the static constructor is called.
public class ViewModelBCreator()
{
private static ViewModelBCreator instance;
static ViewModelBCreator() { instance = new ViewModelBCreator(); }
private ViewModelBCreator()
{
Messaging.Messenger.Default.Register<NotificationMessage>(this, true, NotificationMessageReceived);
}
private static void NotificationMessageReceived(NotificationMessage notification)
{
var vm = ViewModelB();
//Do stuff with the new ViewModelB
}
}
public class ViewModelB
{
public ViewModelB()
{
//etc . . .
}
}
public class ViewModelA
{
public void OpenTheWindow()
{
Messenger.Default.Send(new NotificationMessage("ShowWindow"));
}
}
Upvotes: 2