2012-04-02 42 views
2

我使用Caliburn Micro框架。这实际上并不重要。问题是,我在视图模型中发布了一个事件,其中包含要在其事件参数中显示的新视图模型。该事件在ShellViewModel中捕获(您可以将其视为根视图模型),它实际上激活了新的视图模型。如何在自定义事件参数中传递视图模型

那么我怎么能通过我的事件参数视图模型?目前看起来像这样:

// 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 
    } 
} 

这种方法对我来说似乎不是很优雅。你有更好的想法吗?

回答

2

整体解决方案非常好,您只需将事件参数中的元信息传递给足以创建新ViewModel的事件参数。关于ViewModel创建自己,这是一个标准设计问题,通过实施Factory pattern解决。基本上你需要一个能够创建具体ViewModel类型的工厂,所以你的处理器代码如下:

public void Handle(ViewModelChangedEventArgs message) 
{ 
    var viewModel = viewModelFactory.Create(typeof(AnotherViewModel)); 
} 
相关问题