代码之家  ›  专栏  ›  技术社区  ›  Phil Sandler

与窗口的RelativeSource的WPF绑定需要路径中的“DataContext”?

  •  8
  • Phil Sandler  · 技术社区  · 16 年前

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

        <Style TargetType="TextBox">
            <Setter 
               Property="IsReadOnly"
               Value="{Binding RelativeSource={RelativeSource FindAncestor, 
               AncestorType={x:Type Window}}, Path=DataContext.IsReadOnly}"/>
        </Style>        
    
    1 回复  |  直到 11 年前
        1
  •  13
  •   Luis Filipe    11 年前

    您绑定到包含窗口的DataContext,而不是窗口本身。你要把:

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

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

    推荐文章