开发者

Composite WPF: Data Template vs. View Model Injection

开发者 https://www.devze.com 2023-03-20 12:39 出处:网络
Here is the simple question: what do you use to l开发者_如何学Cink your views to your view models?

Here is the simple question: what do you use to l开发者_如何学Cink 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;
    }
}


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


We use a view model first approach because we find it easier to manage, particular on larger scale enterprise apps. We use Caliburn.Micro to take care of view location and binding.


I use both. DataTemplates for small projects, but for larger or team projects we use view model injection.

0

精彩评论

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