As a continuation of the question Linking DataContext with another property in WPF.
At the very end of the research I was very surprised to find out that when one writes something like that:
<Label Content="{Binding Path=Name}" />
The DataContext against which the Content property is binded is of the Label control itself! The fact that it still works is due to the default inheritance of the DataContext value from the nearest parent.
But if you have this label wrapped in a custom control, and you don’t want to bind your data to the DataContext property of that control, you would more likely love to have:
<Controls:SearchSettings Settings="{Binding Path=Settings}" />
And here you are. Now you need to set Settings as the DataContext for the SearchSettings control, for Label inside to bind against, but you can’t, because that will trigger re-binding of Settings property.
I can’t see the point in mixing binding properties using different sources: DataContext, by ElementName, etc.
So why would I ever use DataContext?
When you write
you are binding to
myLabel.DataContext.Name, and notmyLabel.Name.The XAML in WPF is just a pretty user interface to display and interact with the actual data, otherwise known as the
DataContext. The purpose of other binding sources (RelativeSource,ElementName, etc) is to point to another property that doesn’t exist in the current control’sDataContextSo suppose you have a Window. Without setting the DataContext, the window still displays but there is no data behind it.
Now suppose to set
myWindow.DataContext = new ClassA();. Now the data that the window is displaying isClassA. IfClassAhas a property calledName, I could write a label and bind it toName(such as your example), and whatever value is stored inClassA.Namewould get displayed.Now, suppose
ClassAhas a property ofClassBand both classes have a property calledName. Here is a block of XAML which illustrates the purpose of the DataContext, and an example of how a control would refer to a property not in it’s own DataContextAs you can see, the DataContext is based on whatever data is behind the UI object.
Update: I see this question so often from new WPF users that I expanded this answer into a post on my blog: What is this “DataContext” you speak of?