Flack
Flack

Reputation: 5899

MVVM DataTemplate and non-empty view model constructor

I have the below 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.

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

Upvotes: 4

Views: 1189

Answers (2)

Rachel
Rachel

Reputation: 132548

I don't think Views should be creating ViewModels.

ViewModels should be creating other ViewModels, and the View simply defines how to draw the 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.

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.

Upvotes: 2

devdigital
devdigital

Reputation: 34349

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

Upvotes: 2

Related Questions