在棱镜4.1中,我想使用模块加载功能,并使用mvvm构建项目。现在,我使用目录扫描来注册模块,但是在视图模型中无法导航
模块代码
[Module(ModuleName = "ModuleA", OnDemand = true)]
public class ModuleAModule : IModule
{
private IRegionManager RegionManager { get; set; }
private ViewA ViewA;
public ModuleAModule(IRegionManager RegionManager, IUnityContainer container)
{
if (RegionManager != null)
{
this.RegionManager = RegionManager;
}
if (container != null)
{
this.container = container;
}
}
public void Initialize()
{
this.container.RegisterType<object, ViewA>(nameof(ViewA));
IRegion MathRegion = RegionManager.Regions["ContentRegions"];
MathRegion.Add(this.ViewA, "ViewA");
}
}
然后我从引导程序开始
class Bootstrapper : UnityBootstrapper
{
protected override DependencyObject CreateShell()
{
return ServiceLocator.Current.GetInstance<MainWindow>();
}
protected override void InitializeShell()
{
base.InitializeShell();
Application.Current.MainWindow.Show();
}
protected override IModuleCatalog CreateModuleCatalog()
{
return new DirectoryModuleCatalog() { ModulePath = @".\Modules" };
}
}
我是在视图模型中这样写的
class MainWindowViewModel : NotificationObject
{
private readonly IRegionManager _regionManager;
public DelegateCommand<string> NavigateCommand { get; private set; }
public MainWindowViewModel(IRegionManager regionManager)
{
_regionManager = regionManager;
NavigateCommand = new DelegateCommand<string>(Navigate);
}
private void Navigate(string navigatePath)
{
if (navigatePath != null)
_regionManager.RequestNavigate("ContentRegion", new Uri(navigatePath, UriKind.Relative));
}
}
Xml在MainWindow中:
<DockPanel LastChildFill="True">
<StackPanel Orientation="Horizontal" DockPanel.Dock="Top" Margin="5">
<Button Command="{Binding NavigateCommand}" CommandParameter="ViewA" Margin="5">NavigateCommand A</Button>
</StackPanel>
<TabControl prism:RegionManager.RegionName="ContentRegions" Margin="5"/>
</DockPanel>
public MainWindow(IRegionManager region)
{
InitializeComponent();
this.DataContext = new MainWindowViewModel(region);
}
我现在无法使用按钮进行导航,单击后没有任何反应。是因为注册模块时出错了吗?还是由于其他原因找不到模块?
您想要注册ViewA
进行导航,而不是立即将其添加到该区域。
即:
container.Register<object, ViewA>( nameof(ViewA) );
然后,在RequestNavigate
时,容器将创建一个新实例,而区域管理器会将其放入区域中。