【问题标题】:ViewModel constructor containing arguments ins WPFViewModel 构造函数包含 WPF 中的参数
【发布时间】:2013-09-19 23:55:43
【问题描述】:

当最后一个在他的构造函数中包含参数时,我们如何将用户控件绑定到视图模型对象???

在视图中使用“DataContext”的绑定是否确保当我们创建视图模型时,视图会自动创建??

【问题讨论】:

  • 什么意思?你在使用 IoC 容器吗?如果是,是哪些?请向我们提供更多信息...
  • 我没有找到任何解决方案!我只是在问如何将视图绑定到包含构造函数中参数的视图模型......你能告诉我任何使用 IoC 容器的简单示例吗?
  • 我所有的 ViewModel 都采用构造函数参数。模块加载时的类型注册和实例注册决定了参数的构造方式。

标签: wpf xaml data-binding mvvm user-controls


【解决方案1】:

如果您使用的是 IoC 容器,则支持开箱即用。

这实际上取决于您使用的 IoC 容器,但这里有一个使用 Prism Unity 容器的示例。

以下示例摘自Prism QuickStarts guide

所以,首先,我们必须设置统一容器:

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 框架而有所不同

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-03
    • 2013-02-17
    相关资源
    最近更新 更多