开发者

WPF Binding with RelativeSource of Window Requires "DataContext" in Path?

开发者 https://www.devze.com 2022-12-24 05:56 出处:网络
The followi开发者_如何学Gong code works, but I\'m curious as to why I need the Path to be prefixed with \"DataContext\"?In most other cases, the path used is relative to DataContext.Is it because I am

The followi开发者_如何学Gong code works, but I'm curious as to why I need the Path to be prefixed with "DataContext"? In most other cases, the path used is relative to DataContext. Is it because I am using a RelativeSource? Because the source is at the root level (Window)?

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


You're binding to the containing Window's DataContext, not to the Window itself. Were you to put:

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

This would bind to the IsReadOnly property of the Window, not its data context class. Since Window doesn't contain an IsReadOnly property, this is obviously from a different class (most likely your ViewModel, if you're using MVVM, etc).

0

精彩评论

暂无评论...
验证码 换一张
取 消