如何使用 MEF 初始化 viewModel?

How to initialize viewModel using MEF?

我有一个名为 ModuleMenu 的模块。在这个模块中,我有一个名为 MenuView 的 UserControl 和一个名为 UserControlViewModel 的相应 ViewModel。我还有一个名为 Module 的 class。所有代码如下:

MenuView.xmal

<UserControl ..............>

    <ListBox ItemsSource="{Binding MenuItems, Converter={StaticResource dummy}}" DisplayMemberPath="MenuItemName" SelectedItem="{Binding SelectedMenuItem}" >

        <ListBox.ItemsPanel>
            <ItemsPanelTemplate>
                <StackPanel IsItemsHost="True" Orientation="Horizontal"/>
            </ItemsPanelTemplate>
        </ListBox.ItemsPanel>

        <ListBox.Resources>
            <Style TargetType="ListBoxItem">
                <Setter Property="Margin" Value="10,0" />
            </Style>
        </ListBox.Resources>

    </ListBox>

</UserControl>

MenuView.xaml.cs

[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class MenuView : UserControl
{
    public MenuView()
    {
        InitializeComponent();
    }
}

UserControlViewModel.cs

[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class MenuViewModel : ViewModelBase
{
    IServiceFactory _ServiceFactory;

    [ImportingConstructor]
    public MenuViewModel(IServiceFactory serviceFactory)
    {
        _ServiceFactory = serviceFactory;
    }

    protected override void OnViewLoaded()
    {
        _MenuItems = new ObservableCollection<MenuItem>();

        WithClient<IMenuItemService>(_ServiceFactory.CreateClient<IMenuItemService>(), menuItemClient =>
            {
                MenuItem[] menuItems = menuItemClient.GetAllParentMenuItemsWithChildren();
                if (menuItems != null)
                {
                    foreach (MenuItem menuItem in menuItems)
                    {
                        _MenuItems.Add(menuItem);
                    }

                    _SelectedMenuItem = _MenuItems[2];
                }

            });
    }

    private ObservableCollection<MenuItem> _MenuItems;

    public ObservableCollection<MenuItem> MenuItems
    {
        get
        {
            return _MenuItems;
        }
        set
        {
            if (_MenuItems != value)
            {
                _MenuItems = value;
                OnPropertyChanged(() => MenuItems, false);
            }
        }
    }

    private MenuItem _SelectedMenuItem;

    public MenuItem SelectedMenuItem
    {
        get
        {
            return _SelectedMenuItem;
        }
        set
        {
            if (_SelectedMenuItem != value)
            {
                _SelectedMenuItem = value;
                OnPropertyChanged(() => SelectedMenuItem);
            }
        }
    }

}

Module.cs

[ModuleExport(typeof(Module), InitializationMode=InitializationMode.WhenAvailable)]
public class Module : IModule
{
    IRegionManager _regionManager;

    [ImportingConstructor]
    public Module(IRegionManager regionManager)
    {
        _regionManager = regionManager;
    }

    public void Initialize()
    {
        _regionManager.Regions[RegionNames.MenubarRegion].Add(ServiceLocator.Current.GetInstance<MenuView>());
    }
}

现在在我的主项目中,我有一个名为 BootStrapper.cs 的 class,如下所示:

public class Bootstrapper : MefBootstrapper
{
    protected override DependencyObject CreateShell()
    {
        return Container.GetExportedValue<Shell>();
    }

    protected override void InitializeShell()
    {
        base.InitializeShell();
        App.Current.MainWindow = (Window)Shell;
        App.Current.MainWindow.Show();
    }

    protected override void ConfigureAggregateCatalog()
    {
        base.ConfigureAggregateCatalog();
        AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(Bootstrapper).Assembly));
        AggregateCatalog.Catalogs.Add(new AssemblyCatalog(typeof(ModuleMenu.Module).Assembly));
    }
}

在我的 App.xaml:

<Application ..............>
    <Application.Resources>
        <DataTemplate DataType="{x:Type modMenu:MenuViewModel}">
            <modMenu:MenuView />
        </DataTemplate>
    </Application.Resources>
</Application>

最后在 App.xaml.cs:

public partial class App : Application
{
    protected override void OnStartup(StartupEventArgs e)
    {
        base.OnStartup(e);

        Bootstrapper bootstrapper = new Bootstrapper();
        bootstrapper.Run();

    }
}

当我 运行 应用程序时,我得到了预期的 shell。它向我显示 MenuView,但未加载 MenuView 中的数据。我尝试使用虚拟转换器对其进行调试,结果显示 viewModel 从未初始化。

那么,现在我的问题是如何初始化 viewModel?

更新:

尝试你的代码后,我得到如下异常:

尝试向区域 'MenubarRegion' 添加视图时发生异常。

- The most likely causing exception was was: 
    'Microsoft.Practices.ServiceLocation.ActivationException: Activation  
    error occured while trying to get instance of type MenuView, key "" ---> 
    Microsoft.Practices.ServiceLocation.ActivationException: Activation 
    error occured while trying to get instance of type MenuView, key ""

at Microsoft.Practices.Prism.MefExtensions.MefServiceLocatorAdapter
                  .DoGetInstance(Type serviceType, String key)

at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase
                  .GetInstance(Type serviceType, String key)

--- End of inner exception stack trace ---

at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase
                  .GetInstance(Type serviceType, String key)

at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase
                  .GetInstance(Type serviceType)

at Microsoft.Practices.Prism.Regions.RegionViewRegistry
                  .CreateInstance(Type type)

at Microsoft.Practices.Prism.Regions.RegionViewRegistry
                  .<>c__DisplayClass1.<RegisterViewWithRegion>b__0()

at Microsoft.Practices.Prism.Regions.Behaviors
                  .AutoPopulateRegionBehavior
                  .OnViewRegistered(Object sender, ViewRegisteredEventArgs e)'.

 But also check the InnerExceptions for more detail or call 
                  .GetRootException().

当我查看内部异常时,收到以下错误消息:

{"Activation error occured while trying to get instance of type MenuView, key \"\""}

更新2:

这是 ServiceFactory 类型的导出:

[Export(typeof(IServiceFactory))]
[PartCreationPolicy(CreationPolicy.NonShared)]
public class ServiceFactory : IServiceFactory
{
    public T CreateClient<T>() where T : IServiceContract
    {
        return ObjectBase.Container.GetExportedValue<T>();
    }
}

您将 DataTemplate 定义为视图模型的视图,但实际上并未使用它。

使用 Prism 解决问题的方法有很多,请参考 this topic

您可以在 XAML 中设置 DataContext 属性 视图:

<UserControl.DataContext>
    <my:MyViewModel/>
</UserControl.DataContext>

您可以在视图的构造函数中创建视图模型:

public MyView()
{
    InitializeComponent();
    this.DataContext = new MyViewModel();
}

更好的方法是通过依赖注入导入视图模型:

[ImportingConstructor]
public MyView(MyViewModel viewModel)
{
    InitializeComponent();
    this.DataContext = viewModel;
}

您可以使用 Prism 的视图模型定位服务:

<MyView prism:ViewModelLocator.AutoWireViewModel="True"/>

最后但同样重要的是:您也可以使用 DataTemplate,但您应该设置对象的 DataContext 让 WPF 为您创建视图,而不是创建视图在代码中。


更新: 因此,您想使用 DataTemplate 功能。好吧,这不是 'Prism' 做事的方式,因为在那种情况下,视图将由 WPF 创建,而不是由 Prism 的 IRegion 创建。但无论如何这是可能的。

我将解释区别:在所有其他 (Prism) 方法中,视图是 'master',它将首先创建,然后将创建适当的视图模型并将其附加到视图。在 Prism 中,您可以定义应创建哪些视图、何时(导航)和何处(区域)。在DataTemplate方法中,viewmodel(data)是'master',它会先被创建,WPF在创建视图的时候决定如何显示它们。所以在这种情况下,您不能使用 Prism 的区域和导航,因为 WPF 会处理所有事情。

所以我真的建议您为此使用上述任何一种方法,但不要使用 DataTemplate 方法。

您按如下方式创建视图:

_regionManager.Regions[RegionNames.MenubarRegion].Add(ServiceLocator.Current.GetInstance<MenuView>());

我建议您将其更改为:

_regionManager.RegisterViewWithRegion(RegionNames.MenubarRegion, typeof(MenuView));

直接使用ServiceLocator不是一个好的模式(除非你无法避免),所以让Prism为你实例化视图。

在视图的构造函数中,只需添加视图模型的依赖项注入,并将视图的 DataContext 设置到它。瞧!你明白了。

[Export]
[PartCreationPolicy(CreationPolicy.NonShared)]
public partial class MenuView : UserControl
{
    [ImportingConstructor]
    public MenuView(MenuViewModel viewModel)
    {
        this.InitializeComponent();
        this.DataContext = viewModel;
    }
}

使用DataTemplate,你只能在'old plain WPF way'中完成。您必须手动创建视图模型的实例并将其公开为父(shell 的)视图模型的 属性(或者将其设为静态,但这是一种糟糕的方法)。

<Window>
  <ContentControl Content="{Binding MenuViewModelInstace}"/>
</Window>

WPF 然后将为您创建视图以显示视图模型,但您应该直接在 XAML 标记中定义它,正如我之前提到的。棱镜在这里帮不了你。