Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WPF FindAncestor in binding

Tags:

binding

wpf

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?

like image 789
dbostream Avatar asked Apr 29 '13 12:04

dbostream


1 Answers

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.

like image 194
GazTheDestroyer Avatar answered Sep 16 '22 20:09

GazTheDestroyer