如何在自定义事件args中传递视图模型

时间:2012-04-02 10:38:32

标签: c# .net viewmodel

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

那我怎么能在我的event args中传递视图模型呢?目前它看起来像这样:

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

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

1 个答案:

答案 0 :(得分:2)

整体解决方案非常好,您只需在事件args中传递元信息即可创建新的ViewModel。关于ViewModel创建自身,这是一个标准的设计问题,可以通过实现Factory pattern来解决。基本上你需要一个能够按类型创建具体ViewModel的工厂,所以你的处理程序代码如下所示:

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