Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composite WPF: Data Template vs. View Model Injection

Here is the simple question: what do you use to link your views to your view models?

Basically there is 2 common ways of achieving that, data templates and view model injection (samples below).

What I would like to know is why do you prefer a method over the other and in which case you use them. Precise the MVVM framework you use.


The data template way or "View Model first" approach (Resources.xaml):

<DataTemplate DataType="{x:Type my:PersonViewModel}">
    <my:PersonView/>
</DataTemplate>


The view model injection way or "View first" approach (PersonView.xaml.cs):

[Import]
public PersonViewModel ViewModel
{
    set
    {
        this.DataContext = value;
    }
}
like image 515
Ucodia Avatar asked May 03 '26 08:05

Ucodia


1 Answers

I prefer using DataTemplates

  • It allows me to set multiple Views for the same ViewModel based on a property

  • My ViewModels are my application, and the View is nothing more than a pretty layer that makes my ViewModel's User-Friendly. If I use ViewModel injection, than the Views become my application and the development team suddenly has to worry about the UI side of things

  • My ViewModels are managed by other ViewModels. For example, one ViewModel might contain a collection of other ViewModels that get displayed in a TabControl. Adding or Closing tabs is done within the parent ViewModel. This sort of thing is not easily accomplished with the View controlling the application state.

  • I can initialize different ViewModels using parameterized constructors based on my needs instead of having to use generic Import ones

That's just a few reasons... I'm sure there's others but they don't come to mind right now

like image 85
Rachel Avatar answered May 04 '26 22:05

Rachel