wpftabcontroltabitemfindancestor

WPF findancestor not working on second tabitem


Quite a simple problem (I think!) but I can't seem to find a simple answer for it.

I've build a test WPF app which contains a tabcontrol and two tab items. On each tabitem is a button and it's content is bound to a Path which is stored in a local resource dictionary. The Path's Fill property is bound the button's Foreground property using FindAncestor.

The problem: On tab1 the content displays correctly but on tab2 it doesn't display at all. If I remove the FindAncestor binding and replace with a brush (say, White), both buttons display correctly.

I'm hoping I'm missing something simple because this seems like something that should be possible.

Code:

<Window.Resources>
    <ResourceDictionary>
        <Path x:Key="TickIcon2" Fill="{Binding Foreground, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Control}}}" Stretch="Uniform" x:Shared="False"  Data="F1 M 23.7501,33.25L 34.8334,44.3333L 52.2499,22.1668L 56.9999,26.9168L 34.8334,53.8333L 19.0001,38L 23.7501,33.25 Z"/>
    </ResourceDictionary>
</Window.Resources>
<Grid>
    <TabControl>
        <TabItem Header="1">
            <Button Content="{DynamicResource TickIcon2}"  Width="50" Height="50" />
        </TabItem>
        <TabItem Header="2">
            <Button  Content="{DynamicResource TickIcon2}"  Width="50" Height="50" />
        </TabItem>
    </TabControl>
</Grid>

Solution

  • I found a solution in case someone comes across this problem. If I used 'Binding' instead of 'DynamicResourse' the path displays correctly on both tabs:

    <Grid>
        <TabControl>
            <TabItem Header="1">
                <Button Content="{Binding Mode=OneWay, Source={StaticResource TickIcon2}}"  Width="50" Height="50" />
            </TabItem>
            <TabItem Header="2">
                <Button  Content="{Binding Mode=OneWay, Source={StaticResource TickIcon2}}"  Width="50" Height="50" />
            </TabItem>
        </TabControl>
    </Grid>