这里是新开发人员,正在开发我的第二个应用程序,第一个应用程序使用 Prism 7.1。
我希望在正确访问 Shell.xaml.cs 中注册的 ViewModel 方面获得一些帮助。
这是我正在处理的内容:
App.xaml.cs
public partial class App
{
protected override Window CreateShell()
{
return Container.Resolve<Shell>();
}
protected override void RegisterTypes(IContanerRegistry containerRegistry)
{
containerRegistry.Register<ShellViewModel>();
}
}
Shell.xaml.cs
public partial class Shell : MetroWindow
{
public Shell()
{
InitializeComponent();
}
}
通过执行以下操作,我可以很好地访问 ViewModel 的属性:
var shellVM_Instance = containerProvider.Resolve<ShellViewModel>();
shellVM_Instance.IsBusy = false;
代码可以编译,但不会运行。当我运行代码时,它告诉我 ShellViewModel 从上面的 var shellVM_Instance 中引用了 ShellViewModel 类型的空对象。这让我认为我没有使用 IContainerRegistry 正确注册 ViewModel。
有人可以提供任何帮助吗?
我想避免使用 Bootstrapper 类,并利用 Prism 7.1 提供的功能 ( Brian's Release Notes )
感谢这里的任何指导以及您在我尝试了解 Prism 及其真正潜力时的耐心。
编辑:
我看到 IContainerRegistry 有一个 RegisterInstance 方法..
void RegisterInstance(Type type, object instance);
我一生都无法弄清楚语法。我的尝试:
protected override void RegisterTypes(IContainerRegistry containerRegistry)
{
ShellViewModel shell_VM = new ShellViewModel();
containerRegistry.RegisterInstance<ShellViewModel, shell_VM>();
}
谢谢!
-克里斯
最佳答案
有IContainerRegistry
和 IContainerRegistryExtensions
.
所以你可以做任何一个
containerRegistry.RegisterInstance( typeof( ShellViewModel ), shell_VM );
或者一般使用扩展方法
containerRegistry.RegisterInstance<ShellViewModel>( shell_VM );
最好注册为单例,以防万一您有任何依赖项(否则您必须自己解决)
containerRegistry.RegisterSingleton<ShellViewModel>();
话虽如此,你从一开始就做错了。 View 模型很少是单例。相反,让您的 View 模型通过第三方单例(EventAggregator
或您自己的服务之一)进行通信。对于你的情况,我建议这样:
public interface IApplicationBusyIndicator : INotifyPropertyChanged
{
bool IsBusy { get; set; }
}
然后让 shell View 模型监视 IsBusy
的更改并激活或停用您的等待覆盖,而其他 View 模型或服务在执行时设置 IsBusy
东西。当然,如果您碰巧有多个参与者使应用程序繁忙并且这些操作重叠,那么您可以使其更加复杂......
public interface IApplicationBusySetter
{
IDisposable RequestBusy();
}
然后显示等待屏幕,直到处理完所有请求。
关于c# - Prism 7.1 : IContainerProvider & IContainerRegistry,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56741827/