使用IEventAgrrregator作为参数的ViewModel构造函数

时间:2018-02-19 08:52:26

标签: wpf mvvm eventaggregator prism-6 viewmodellocator

在我的应用程序中,我通常使用没有任何参数的ViewModel构造函数,并从xaml中找到我的ViewModel,如下所示。

<UserControl.Resources>
    <ResourceDictionary>
        <vm:TabViewModel  x:Key ="vm" ></vm:TabViewModel>
    </ResourceDictionary>
</UserControl.Resources>

通过使用它,我可以在设计时轻松地在xaml中引用我的ViewModel属性。

<Grid x:Name="grid" DataContext="{Binding Source={StaticResource ResourceKey=vm}}">

但是,由于我将在两个ViewModel之间进行通信,因此我开始使用 Prism 6 (Event Aggregator)。

public TabViewModel(IEventAggregator eventAggregator)
    {
        this.eventAggregator = eventAggregator;
        tabPoco = new TabWindowPoco();

        tabPoco.Tag = "tag";
        tabPoco.Title = "Title";

        tabPoco.ListDataList = new ObservableCollection<ListData>();

        tabPoco.ListDataList.Add(new ListData() { Name = "First", Age = 10, Country = "Belgium" });
        tabPoco.ListDataList.Add(new ListData() { Name = "Second", Age = 11, Country = "USA" });
        tabPoco.ListDataList.Add(new ListData() { Name = "Third", Age = 12, Country = "France" });
    }

我正在使用 Bootstrapper 来加载应用程序。

由于我使用的是IEventAggregator,因此我强制使用prism:ViewModelLocator.AutoWireViewModel =“True”来定位ViewModel。否则,应用程序不会运行。现在,我无法将ViewModel用作资源,也无法将其附加到DataContext。

我不希望Prism自动定位相应的ViewModel,我想控制它。我想在xaml中找到它并将其分配给DataContext。

有谁知道我如何实现这个目标?

1 个答案:

答案 0 :(得分:1)

这看起来您未能设置依赖注入容器。接口类型和具体类型之间的Dependency injection uses a preset mapping。您的映射看起来与此类似(Prism / EntLib 5示例):

public class Bootstrapper : UnityBootstrapper
{
    protected override void ConfigureContainer()
    {
        base.ConfigureContainer();

        this.Container.RegisterType<IMyViewModel, SomeViewModel>();
        this.Container.RegisterType<IFooViewModel, SomeOtherViewModel>();
    }
}

稍后您拨打电话时:

this.DataContext = container.Resolve<IMyViewModel>();

这比这个小例子建议的更强大 - 你可以从容器(或区域管理器)新建一个视图,最终自动解析所有依赖项。

要在XAML中维护intellisense等,您可以在XAML中指定viewmodel的类型

<UserControl x:Class="YourNamespace.YourFancyView"
             ...
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:myNamespaceAlias="clr-namespace:PathToMyViewModelsInterface" 
             mc:Ignorable="d" 
             d:DesignHeight="100" d:DesignWidth="100"
             d:DataContext="{d:DesignInstance myNamespaceAlias:IMyViewModel, IsDesignTimeCreatable=False}" 
             ...
             >
</UserControl>

查看相关的SO问题How do I specify DataContext (ViewModel) type to get design-time binding checking in XAML editor without creating a ViewModel object?Using Design-time Databinding While Developing a WPF User Control以获取更多信息。