What is the difference between a DataTemplate and a DataContext in WPF?

I can establish a relationship between the View Model and the view using the following syntax DataContext:

 <UserControl.DataContext>
    <view_model:MainMenuModel />
</UserControl.DataContext>

And I can also establish a connection between the View Model and view using the syntax DataTemplate:

    <DataTemplate
        DataType="{x:Type viewModel:UserViewModel}">
        <view:UserView />
    </DataTemplate>

What is the difference between the two? Is the second XAML not to configure the view data context?

+5
source share
2 answers

The second XAML defines a template that can be used to display an object of type viewModel:UserViewModel. It does not set the data for anything, but if a is ContentPresenterasked to display an object of this type, it will use your template.

XAML DataContext . , , , DataContext ( ). DataContext ( , "s" - System):

<StackPanel>  
  <TextBlock Text="{Binding Day, Source={x:Static s:DateTime.Now}}" />
  <TextBlock Text="{Binding Month, Source={x:Static s:DateTime.Now}}" />
  <TextBlock Text="{Binding Year, Source={x:Static s:DateTime.Now}}" />
</StackPanel>

<StackPanel DataContext="{Binding Source={x:Static s:DateTime.Now}}">  
  <TextBlock Text="{Binding Day}" />
  <TextBlock Text="{Binding Month}" />
  <TextBlock Text="{Binding Year}" />
</StackPanel>

StackPanels , . (: , .)

+8

DataContext DataContext - , . object. MVVM ViewModel, . , FrameworkElement. .

WPF - , (, UIElement, , DataTemplate , , UserViewModel UserView, UserViewModel, UserView.

. , , ObservableCollection<object>, Foo Bar. DataTemplate Foo Bar. ItemsControl. DataTemplate .

: ViewModel DisplayObject, , DataTemplate, , ContentPresenter:

<ContentPresenter DataContext="{Binding DisplayObject}"/>

, , WPF .

+2

All Articles