WPF与窗口的RelativeSource绑定(bind)需要路径中的 "DataContext"?

标签 wpf data-binding

以下代码有效,但我很好奇为什么我需要以“DataContext”为前缀的路径?在大多数其他情况下,使用的路径是相对于 DataContext 的。是因为我使用的是RelativeSource吗?因为源是在根级别(窗口)?

    <Style TargetType="TextBox">
        <Setter 
           Property="IsReadOnly"
           Value="{Binding RelativeSource={RelativeSource FindAncestor, 
           AncestorType={x:Type Window}}, Path=DataContext.IsReadOnly}"/>
    </Style>        

最佳答案

您正在绑定(bind)到包含 Window 的 DataContext,而不是 Window 本身。你要说:

Value="{Binding RelativeSource={RelativeSource FindAncestor, 
       AncestorType={x:Type Window}}, Path=IsReadOnly}"

这将绑定(bind)到 IsReadOnly Window 的属性,而不是它的数据上下文类。从 Window doesn't contain an IsReadOnly property ,这显然来自不同的类(很可能是您的 ViewModel,如果您使用的是 MVVM 等)。

关于WPF与窗口的RelativeSource绑定(bind)需要路径中的 "DataContext"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2493389/

相关文章:

c# - 添加项目后组合框不刷新 C# WPF

c# - 如何在 WPF 中将窗口设置为 ViewModel 的所有者

wpf - 绑定(bind)到 datacontext parent-WPF 的属性

java - JFace数据绑定(bind): Update model only if all validators succeed

c# - WPF - 将 Storyboard放入资源字典

c# - 检测 PropertyChangedEventHandler 何时更改

javascript - 将 Javascript 对象绑定(bind)到 HTML 元素

c# - 如何创建尽可能多的相同数据绑定(bind)组合框,但从相同的字段名称中提取不同的值?

data-binding - 使父类(super class)字段可见

c# - WinForms 上的单向绑定(bind)?