WPF FindAncestor in binding

27,397

From the MSDN page about the RelativeSource.Mode property:

If this property is not set explicitly, setting the AncestorType or the AncestorType and the AncestorLevel properties will implicitly lock this property value to FindAncestor.

Share:
27,397

Related videos on Youtube

Author by

dbostream

Updated on April 30, 2020

Comments

  • dbostream over 2 years

    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?