I’ve been working with MVVM for a while, and this problem (if it is a problem) has me stumped all the time.
I have an ItemsControl bound to a collection in my MainViewModel
ViewModel
public class MainViewModel : ViewModelBase
{
public ObservableCollection<string> Names { get; set; }
}
XAML
<ItemsControl ItemsSource="{Binding Names}">
<ItemsControl.ItemTemplate>
<DataTemplate>
<view:NameView />
</DataTemplate>
</ItemsControl.ItemTemplate>
</ItemsControl>
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).
I hope that makes sense.
Why not do the following?
This seems a bit odd, but AFAIK there isn’t a specific prohibition against one VM knowing about others.
In a case where you use DI for VM resolution, obviously your design would have to be adjusted. For instance, you might create a
NamesViewwhich is a UserControl with a publicDependencyPropertyof typeIEnumerable<string>. Then, theNamesView‘s ViewModel is bound to this DP…