使用 MVVM 分配数据上下文的最佳方法是什么? [英] 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
在视图上分配数据上下文(在 XAML 或代码隐藏上).
Assign data context on View (either on XAML or code behind).
通过构造函数在 ViewModel 上分配数据上下文.
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?
推荐答案
我个人喜欢 这种方法 因为它使我不得不编写更少的代码:).它基本上使用 IValueConverter
来查找要使用的视图,只要 wpf 控件需要在视觉上呈现 ViewModel
并且 IValueConverter
为您设置数据上下文.它还向您展示了如何创建允许您要求 WPF 默认使用此转换器的数据模板,如下所示:
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>
这篇关于使用 MVVM 分配数据上下文的最佳方法是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!