Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

The following 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>        
like image 204
Phil Sandler Avatar asked Mar 22 '10 15:03

Phil Sandler


1 Answers

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).

like image 97
Reed Copsey Avatar answered Nov 15 '22 22:11

Reed Copsey