Question

In a wpf Window I use DataContext="{Binding RelativeSource={RelativeSource Self}}" so that I can bind e.g. to a UserControl UserControl="{Binding ElementName=Information}".

When I remove the DataContext line, the Binding to ElementName also works.
Also when I set another DataContext e.g. this.DataContext = new MainViewModel(); it works.

How then works the binding via ElementName when it is not using DataContext?

Was it helpful?

Solution

When using ElementName, the Binding.Source value is implicitly set to the object that it refers to. This is one way that we can Bind without setting a DataContext. From the Binding.ElementName Property page on MSDN:

By default, bindings inherit the data context specified by the DataContext property, if one has been set. However, the ElementName property is one of the ways you can explicitly set the source of a Binding and override the inherited data context.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top