【问题标题】:WPF Binding with RelativeSource of Window Requires "DataContext" in Path?WPF与Window的RelativeSource绑定需要路径中的“DataContext”?
【发布时间】:2010-03-22 15:19:10
【问题描述】:

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

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

【问题讨论】:

    标签: wpf data-binding


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-06-28
      • 1970-01-01
      • 1970-01-01
      • 2012-12-25
      • 2012-09-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多