MVVM DataTemplate and non-empty view model constructor

I have the following DataTemplate:

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

The fact is that my view model has a constructor that accepts parameters that are automatically inserted by the container (unity). In order for the DataTemplate to work, MyViewModel must have a constructor without a pair.

Is there any other way that I can insert the appropriate values ​​into my view model if I use a DataTemplate to create it?

+4
source share
2 answers

I do not think that Views should create ViewModels.

ViewModels must create other ViewModels, and the view simply determines how to draw the ViewModel.

For example, a ParentViewModel may have a ChildViewModel property. ParentView will contain a ContentControl whose content is bound to the ChildViewModel , and the DataTemplate will be used to tell the application that it is drawing the ChildViewModel as a ChildView .

With that said, how is your View currently creating your ViewModel? You can always add DependencyProperties to your view and create your ViewModel in the loaded View event using these properties.

+2
source

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

+2
source

All Articles