Search code examples
mvvmdatacontext

Why do I have to declare DataContext when binding to relative source


When I bind I normally just enter the name of the property which exists in the DataContext

EG

Text = {Binding MyProp}"

When I use relative source, I have to use DataContext

Text = "{Binding RelativeSource={RelativeSource AncestorLevel=1, AncestorType={x:Type UserControl}, Mode=FindAncestor}, Path=DataContext.MyProp }" />

I must be missing some basic understanding as I don't see why I need to include the word DataContext in the path: Path=DataContext.MyProp, I had assumed it has implicit. If I remove DataContext from the string, then it won't bind.


Solution

  • RelativeSource will change the target to, in this instance, UserControl. This way you can bind to elements on the UserControl, such as its Width/Height/etc. In these cases having an implicit DataContext would be counter-productive.