开发者

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

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 s开发者_开发问答ome infrastructure classes.

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


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>


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...

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜