2010-03-22 76 views
8

下面的代碼有效,但我很好奇爲什麼我需要將路徑添加到前綴「DataContext」?在大多數情況下,使用的路徑與DataContext相關。是因爲我在使用RelativeSource嗎?因爲源是在根級(窗口)?WPF與窗口的RelativeSource綁定需要路徑中的「DataContext」?

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

回答

13

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

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

這將綁定到窗口的IsReadOnly屬性,而不是它的數據上下文類。由於Window doesn't contain an IsReadOnly property,這顯然來自不同的類(如果您使用的是MVVM等,很可能是您的ViewModel)。

+0

有道理。謝謝。 – 2010-03-22 15:26:25