当最后一个在他的构造函数中包含参数时,我们如何将用户控件绑定到视图模型对象?
在视图中使用“DataContext”的绑定是否确保当我们创建视图模型时,视图会自动创建?
当最后一个在他的构造函数中包含参数时,我们如何将用户控件绑定到视图模型对象?
在视图中使用“DataContext”的绑定是否确保当我们创建视图模型时,视图会自动创建?
如果您使用的是 IoC 容器,则支持开箱即用。
这实际上取决于您使用的 IoC 容器,但这里是使用 Prism Unity 容器的示例。
以下示例摘自Prism 快速入门指南
因此,首先,我们必须设置统一容器:
public class QuickStartBootstrapper : UnityBootstrapper
{
private readonly CallbackLogger callbackLogger = new CallbackLogger();
/// <summary>
/// Configures the <see cref="IUnityContainer"/>.
///May be overwritten in a derived class to add specific
/// type mappings required by the application.
/// </summary>
protected override void ConfigureContainer()
{
// Here you can do custom registeration of specific types and instances
// For example
this.Container.RegisterInstance<CallbackLogger>(this.callbackLogger);
base.ConfigureContainer();
}
}
基本上,你完成了!您现在要做的就是让您的视图在其构造函数中接收 viewModel 作为参数,如下所示:
public partial class OverviewView
{
public OverviewView(OverviewViewModel viewModel)
{
InitializeComponent();
this.DataContext = viewModel;
}
}
Unity IoC 容器将处理您在 ViewModel 中的参数,即使您大部分时间都不必注册这些类型。
请注意,在我的回答中,我只提到了配置的 IoC 部分。设置整个 MVVM 应用程序需要更多的工作,并且取决于您使用的 MVVM 框架