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

僤鯓⒐⒋嵵緔 提交于 2020-02-17 07:35:41

问题


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?


回答1:


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>



回答2:


the 4. way would be a DataTemplate.

i think the best approach is the one which fits best in your current situation.

if i have viewmodel first dynamic scenarios i use datatemplate/contentpresenter or with view first i take your way one and so on...



来源:https://stackoverflow.com/questions/5853586/what-is-the-best-approach-to-assign-data-context-using-mvvm

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!