为什么在绑定到相对源时必须声明 DataContext

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

当我绑定时,我通常只输入存在于 DataContext

中的 属性 的名称

EG

Text = {Binding MyProp}"

当我使用相对源时,我必须使用 DataContext

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

我一定是缺少一些基本的理解,因为我不明白为什么我需要在路径中包含 DataContext 这个词:Path=DataContext.MyProp,我曾假设它是隐含的。如果我从字符串中删除 DataContext,则它不会绑定。

RelativeSource 会将目标更改为(在本例中为 UserControl)。这样您就可以绑定到 UserControl 上的元素,例如它的 Width/Height/etc。在这些情况下,使用隐式 DataContext 会适得其反。