如何基于 DataTemplate 的 DataContext 对象创建 ViewModel? [英] How do I create a ViewModel based on the DataContext object of a DataTemplate?
问题描述
我使用 MVVM 已经有一段时间了,这个问题(如果是问题的话)一直困扰着我.
I've been working with MVVM for a while, and this problem (if it is a problem) has me stumped all the time.
我有一个 ItemsControl 绑定到我的 MainViewModel 中的一个集合
I have an ItemsControl bound to a collection in my MainViewModel
视图模型
public class MainViewModel : ViewModelBase
{
public ObservableCollection<string> Names { get; set; }
}
XAML
<ItemsControl ItemsSource="{Binding Names}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<view:NameView />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
每个的 DataContext 属性都是字符串类型(直接绑定到模型),但是如果我希望 DataContext 绑定到基于该属性的 ViewModel 该怎么办.我将如何实例化 ViewModel 并将其提供给模型(字符串).
The DataContext property of each is of type string (bound directly to the Model), but what if I wanted the DataContext's to be bound to a ViewModel which is based on the property. How would I go about instantiating the ViewModel and feeding it the Model (string).
我希望这是有道理的.
推荐答案
为什么不做以下事情?
public ObservableCollection<NameViewModel> Names { get; set; }
这似乎有点奇怪,但 AFAIK 并没有具体禁止一个 VM 了解其他 VM.
This seems a bit odd, but AFAIK there isn't a specific prohibition against one VM knowing about others.
如果您将 DI 用于 VM 分辨率,显然您的设计必须进行调整.例如,您可以创建一个 NamesView
,它是一个具有 IEnumerable
类型的公共 DependencyProperty
的 UserControl.然后,NamesView
的 ViewModel 绑定到这个 DP...
In a case where you use DI for VM resolution, obviously your design would have to be adjusted. For instance, you might create a NamesView
which is a UserControl with a public DependencyProperty
of type IEnumerable<string>
. Then, the NamesView
's ViewModel is bound to this DP...
这篇关于如何基于 DataTemplate 的 DataContext 对象创建 ViewModel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!