I can set the relationship between View Model and view through following DataContext syntax:
<UserControl.DataContext>
<view_model:MainMenuModel />
</UserControl.DataContext>
And I can also set the relationship between View Model and view through following DataTemplate syntax:
<DataTemplate
DataType="{x:Type viewModel:UserViewModel}">
<view:UserView />
</DataTemplate>
What is the difference between the two? Is the second XAML not setting the data context of a view?
Your second XAML defines a template that can be used to display an object of type
viewModel:UserViewModel. It doesn’t set data for anything but, if aContentPresenteris asked to display an object of that type, it will use your template.Your first XAML is setting the
DataContextproperty of your control. It defines that any bindings you perform within that scope will use theDataContextas the root of the binding (unless explicitly overriden). For a simple example ofDataContextat work, compare these two (both assume that “s” is theSystemnamespace):Both
StackPanelswill render identically, but the second is more easily reused. (E.g.: you only have to change the binding in one place if you wanted to display a different date.)