Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best approach to assign Data Context using MVVM?

Tags:

mvvm

wpf

I was looking for best approach to set data context property. I found three ways

  1. Assign data context on View (either on XAML or code behind).

  2. Assign data context on ViewModel through constructor.

  3. Use some configuration that takes view and view model reference and bind data context on run time through some infrastructure classes.

Which is the best option among this in terms of loosely coupled, maintainable? Or Is there any best approach?

like image 397
pchajer Avatar asked May 02 '11 04:05

pchajer


People also ask

When should MVVM be used?

MVVM separates your view (i.e. Activity s and Fragment s) from your business logic. MVVM is enough for small projects, but when your codebase becomes huge, your ViewModel s start bloating. Separating responsibilities becomes hard. MVVM with Clean Architecture is pretty good in such cases.

Is MVVM deprecated?

This is the same MVVM library used by the Microsoft Store, the Photos app, and more! The MVVM Toolkit is inspired by MvvmLight, and is also the official replacement for it now that the library has been deprecated.


1 Answers

I personally like this approach because it makes me have to write less code :). It basically uses an IValueConverter to lookup which view to use whenever a wpf control needs to present a ViewModel visually and the IValueConverter sets the datacontext for you. It also shows you how to create a datatemplate that allows you to require WPF to utilize this converter by default, something like this:

<DataTemplate DataType="{x:Type ViewModels:ViewModelBase}">
    <ContentControl Content="{Binding Converter={StaticResource MyConverter}}"/>
</DataTemplate>
like image 96
Jose Avatar answered Oct 19 '22 23:10

Jose