7

One particular thing about FindAncestor confuses me, have a look at the example below:

<Expander.HeaderTemplate>
    <DataTemplate>
        <StackPanel Orientation="Horizontal">
            <Label Name="headerLabel"  Content="Show Contents" Padding="0" VerticalAlignment="Center" />
            <Button Name="headerButton" Margin="6,0,0,0" Content="Button" Padding="6,1" />
        </StackPanel>
        <DataTemplate.Triggers>
            <DataTrigger Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Expander}}, Path=IsExpanded}" Value="True">
                <Setter TargetName="headerLabel" Property="Content" Value="Hide Contents" />
            </DataTrigger>
        </DataTemplate.Triggers>
    </DataTemplate>
</Expander.HeaderTemplate>

I use the xaml above to change the text of my custom expander header. My question is, when do I actually need to explicitly use FindAncestor when I want to use a property of an ancestor in my binding? Because the following three bindings appear to yield the same result in my scenario at least:

Binding="{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType={x:Type Expander}}, Path=IsExpanded}"

Binding="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Expander}}, Path=IsExpanded}" 

Binding="{Binding RelativeSource={RelativeSource AncestorType={x:Type Expander}}, Path=IsExpanded}"

I have seen lots of examples of all three, is it just a matter of personal taste?

4

1 に答える 1