WPF使用Window的RelativeSource绑定需要在路径中包含"DataContext"吗?

9
下面的代码可以工作,但是我想知道为什么需要在路径前面加上“DataContext”?在大多数其他情况下,使用的路径都是相对于DataContext的。这是因为我使用了RelativeSource吗?因为源位于根级别(Window)?
    <Style TargetType="TextBox">
        <Setter 
           Property="IsReadOnly"
           Value="{Binding RelativeSource={RelativeSource FindAncestor, 
           AncestorType={x:Type Window}}, Path=DataContext.IsReadOnly}"/>
    </Style>        
1个回答

20

你正在绑定到包含窗口的数据上下文,而不是窗口本身。如果你这样做:

Value="{Binding RelativeSource={RelativeSource FindAncestor, 
       AncestorType={x:Type Window}}, Path=IsReadOnly}"
这将绑定到窗口的IsReadOnly属性,而不是它的数据上下文类。由于Window没有包含IsReadOnly属性,显然这来自于另一个类(如果你使用MVVM等,则很可能是你的ViewModel)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接