I was looking for best approach to set data context property. I found three ways
Assign data context on View (either on XAML or code behind).
Assign data context on ViewModel through constructor.
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?
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.
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.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With