The DataContext
of a FrameworkElement
is what the element is bound to. It is fundamentally of type object
. In the MVVM pattern, this is most frequently the ViewModel object, but it need not be. It is simply some context information you want to apply to that FrameworkElement
. It does not directly affect the visual representation, by itself.
When WPF wants to display some object that doesn't have it's own visual representation (e.g. isn't descended from UIElement
, it will look to see if a corresponding DataTemplate
exists to define how it should present that data. In your example, you have said that the UserViewModel
class should be presented using the UserView
control, but you have not actually created either the UserViewModel
or UserView
.
These two concepts often go together. For example, imagine you had an ObservableCollection<object>
which had in it a Foo
and a Bar
object. You could define different DataTemplate
s for Foo
and Bar
. Then you could bind your collection into an ItemsControl
. Each object in the control would get a visual representation based on the appropriate DataTemplate
from its type.
Another simple example: if you have a property on your ViewModel named DisplayObject
and you simply want it to appear with whatever DataTemplate
you have defined, you can use the ContentPresenter
control:
<ContentPresenter DataContext="{Binding DisplayObject}"/>
Again, this results in WPF looking up the correct Template for the type and using that to construct a representation.