开发者

MVVM DataTemplate and non-empty view model constructor

I have the below DataTemplate:

开发者_JAVA百科    <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?


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜