I use the Caliburn Micro framework. That doesn’t actually matter. The point is, that I publish an event in a view model, which contains the new view model to be shown in its event args. The event gets catched in the ShellViewModel (you could see it as the root view model), which actually activates the new view model.
So how could I pass the view model in my event args? Currently it looks like this:
// where it gets published; "AnotherViewModel" is the actual class
public void AMethod()
{
var args = new ViewModelChangedEventArgs { ViewModelType = typeof(AnotherViewModel) };
PublishEvent(args);
}
// event handler
public void Handle(ViewModelChangedEventArgs message)
{
if (message.ViewModelType == typeof(AnotherViewModel))
{
// activate AnotherViewModel
}
if (message.ViewModelType == typeof(FooViewModel))
{
// activate FooViewModel
}
}
This method seems not very elegant to me. Do you have any better ideas?
Overall solution is pretty well, you just passing a meta information in the event args which is enough to create a new ViewModel. Regarding ViewModel creating itself, this is a standard design problem which is solved by implementing Factory pattern. Basically you need a factory which is able creating concrete ViewModel by a type, so your handler code would be like below: