我一直在尝试将我的 ModuleCatalog 中的模块注入(inject)到我的 Shell 的 ViewModel 中,但我运气不太好...
我正在我的 Bootstrapper 中创建 ModuleCatalog,我的模块从它的 Initializer 进入屏幕没有问题。但是,我希望能够将我的模块列表绑定(bind)到一个带有 DataTemplate 的容器,这样它们就可以从菜单中启动!
这是我的 Boostrapper 文件,随着时间的推移我将添加更多模块,但现在,它只包含我相当做作的“ProductAModule”:
public class Bootstrapper : UnityBootstrapper
{
protected override void ConfigureContainer()
{
Container.RegisterType<IProductModule>();
base.ConfigureContainer();
}
protected override IModuleCatalog GetModuleCatalog()
{
return new ModuleCatalog()
.AddModule(typeof(ProductAModule));
}
protected override DependencyObject CreateShell()
{
var view = Container.Resolve<ShellView>();
var viewModel = Container.Resolve<ShellViewModel>();
view.DataContext = viewModel;
view.Show();
return view;
}
}
接着,这是我的 Shell 的 ViewModel:
public class ShellViewModel : ViewModelBase
{
public List<IProductModule> Modules { get; set; }
public ShellViewModel(List<IProductModule> modules)
{
modules.Sort((a, b) => a.Name.CompareTo(b));
Modules = modules;
}
}
如您所见,我正在尝试注入(inject)一个 IProductModule 列表(ProductAModule 继承了它的一些属性和方法),以便它可以绑定(bind)到我的 Shell View 。是不是我遗漏了一些非常简单的东西,或者不能使用 Unity IoC 来完成? (我已经看到它是用 StructureMap 的 Prism 扩展完成的)
还有一件事......当运行应用程序时,在 Bootstrapper 中的 Container 解析 ShellViewModel 时,我收到以下异常:
Resolution of the dependency failed, type = "PrismBasic.Shell.ViewModels.ShellViewModel", name = "". Exception message is: The current build operation (build key Build Key[PrismBasic.Shell.ViewModels.ShellViewModel, null]) failed: The parameter modules could not be resolved when attempting to call constructor PrismBasic.Shell.ViewModels.ShellViewModel(System.Collections.Generic.List`1[[PrismBasic.ModuleBase.IProductModule, PrismBasic.ModuleBase, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null]] modules). (Strategy type BuildPlanStrategy, index 3)
总之,简单吧...看起来很困惑...
如有任何帮助,我们将不胜感激!
罗布
最佳答案
我想你可以这样做:
public class Bootstrapper : UnityBootstrapper
{
protected override void ConfigureContainer()
{
Container.RegisterType<IProductModule>();
base.ConfigureContainer();
}
private static ObservableCollection<IProductModule> _productModules = new Obser...();
public static ObservableCollection<IProductModule> ProductModules
{
get { return _productModules; }
}
protected override IModuleCatalog GetModuleCatalog()
{
var modCatalog = new ModuleCatalog()
.AddModule(typeof(ProductAModule));
//TODO: add all modules to ProductModules collection
return modCatalog;
}
...
}
然后您将拥有一个静态属性,任何东西都可以直接绑定(bind)到该属性,或者可以从您的 ViewModel 使用。
这里是如何获取已在模块目录中注册的模块名称列表。
public class MyViewModel : ViewModel
{
public ObservableCollection<string> ModuleNames { ... }
public MyViewModel(IModuleCatalog catalog)
{
ModuleNames = new ObservableCollection<string>(catalog.Modules.Select(mod => mod.ModuleName));
}
}
差不多就这些了。 IModuleCatalog 和 IModuleManager 是唯一在容器中设置的东西,供您根据模块访问。不过正如我所说,您不会获得任何实例数据,因为这些模块(希望如此)尚未创建。您只能访问类型数据。
希望这对您有所帮助。
关于c# - Prism 2.1 将模块注入(inject) ViewModel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2113011/