MVVM DataTemplate和非空视图模型构造函数

时间:2022-03-10 22:45:58

I have the below DataTemplate:

我有以下DataTemplate:

    <DataTemplate DataType="{x:Type vm:MyViewModel}">
        <views:MyView/>
    </DataTemplate>

The thing is, my view model has a constructor that takes parameters which are automatically injected by the container (unity). In order for the DataTemplate to work though, MyViewModel needs to have a paramaterless constructor.

问题是,我的视图模型有一个构造函数,它接受由容器自动注入的参数(单位)。为了使DataTemplate工作,MyViewModel需要一个无参数的构造函数。

Is there any other way I can inject the appropriate values into my view model if I am using a DataTemplate to create it?

如果我使用DataTemplate创建它,还有其他方法可以将适当的值注入我的视图模型吗?

2 个解决方案

#1


2  

I don't think Views should be creating ViewModels.

我不认为Views应该创建ViewModels。

ViewModels should be creating other ViewModels, and the View simply defines how to draw the ViewModel.

ViewModels应该创建其他ViewModel,而View只是定义了如何绘制ViewModel。

For example, a ParentViewModel might have a property called ChildViewModel. The ParentView will contain a ContentControl which has its Content bound to ChildViewModel, and a DataTemplate would be used to tell the application to draw ChildViewModel as a ChildView.

例如,ParentViewModel可能具有名为ChildViewModel的属性。 ParentView将包含一个ContentControl,其内容绑定到ChildViewModel,DataTemplate将用于告诉应用程序将ChildViewModel绘制为ChildView。

With that being said, how is your View currently creating your ViewModel? You could always add DependencyProperties to your View and build your ViewModel in the View's loaded event using these properties.

话虽如此,您的View目前是如何创建ViewModel的?您始终可以将DependencyProperties添加到View中,并使用这些属性在View的加载事件中构建ViewModel。

#2


2  

You might want to consider using an MVVM framework such as Caliburn.Micro, and take a ViewModel first approach.

您可能需要考虑使用诸如Caliburn.Micro之类的MVVM框架,并采用ViewModel的第一种方法。

#1


2  

I don't think Views should be creating ViewModels.

我不认为Views应该创建ViewModels。

ViewModels should be creating other ViewModels, and the View simply defines how to draw the ViewModel.

ViewModels应该创建其他ViewModel,而View只是定义了如何绘制ViewModel。

For example, a ParentViewModel might have a property called ChildViewModel. The ParentView will contain a ContentControl which has its Content bound to ChildViewModel, and a DataTemplate would be used to tell the application to draw ChildViewModel as a ChildView.

例如,ParentViewModel可能具有名为ChildViewModel的属性。 ParentView将包含一个ContentControl,其内容绑定到ChildViewModel,DataTemplate将用于告诉应用程序将ChildViewModel绘制为ChildView。

With that being said, how is your View currently creating your ViewModel? You could always add DependencyProperties to your View and build your ViewModel in the View's loaded event using these properties.

话虽如此,您的View目前是如何创建ViewModel的?您始终可以将DependencyProperties添加到View中,并使用这些属性在View的加载事件中构建ViewModel。

#2


2  

You might want to consider using an MVVM framework such as Caliburn.Micro, and take a ViewModel first approach.

您可能需要考虑使用诸如Caliburn.Micro之类的MVVM框架,并采用ViewModel的第一种方法。