WPF: What is the difference between the Content and DataContext properties?
.net, c#, wpf
Solution
`DataContext` is a more general feature in WPF, as suggested by its ownership by the low-level FrameworkElement class.
- it participates in bindings for all framework elements, as the default binding source.
- as you mentioned, an element's DataContext is passed down to child elements.
`Content` is much more specific:
- it is a dependency property specific to a very limited set of controls (mostly those controls that inherit from `ContentControl` -- other controls such as `ListBox` do not own a Content property themselves, but use a ContentControl somewhere in their control templates).
- it is not passed down like the DataContext, but is rather concerned solely with the owning Control and its immediate relationships (ie, bindings)
- it is used by controls that call for something to be displayed, where the control itself does not know or care what type of object that will be.
- it is often used in cojunction with `ContentTemplate` -- that is, Content is what to display, and ContentTemplate is how to display it. (`Button` is a good example of this.)
Problem
As I understand it... - DataContext property - "controls use this property as a data source" - "is a property that each framework element has that can be used to flow data into the screen" - "DataContext has scope" - "the scope is established according to where the DataContext is assigned to in the object tree" - "if you set the DataContext on a parent element (e.g. a Window), that property will flow down to all child elements (e.g. a text box)" - Content property - This property takes on many names depending on the control that is being used: - ContentControl.Content - ItemsControl.ItemsSource - Items.ItemsSource - HeaderedContentControl.Header - HeaderedContentControl.Content So my question is: what is the difference between the `Content` and `DataContext` properties? There is a nuance here that I am missing. Is it... - While the `DataContext` flows data into the UI, - It is the job of the `Content` property to determine (usually threw a binding) what will be displayed (via ContentPresenter + ContentTemplate) SAMPLE CODE ``` <Window x:Name="myWindow" DataContext="{Binding ClassA}> <StackPanel> <!-- DataContext is set to ClassA --> <!-- DataContext is set to ClassA, ClassA.Name will be displayed --> <Label Content="{Binding Name}" /> </StackPanel> </Window> ``` REFERENCES - MSDN: ContentControl.Content Property - MSDN: FrameworkElement.DataContext Property - MSDN: WPF Content Model - worth reading - StackOverflow: What is DataContext for?