tavier
tavier

Reputation: 1794

How to bind property of level2 templated children from the level0 templated parent

I have a Control template defined for my custom control say ControlA:

<Style TargetType="local:ControlA">
    <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="local:ControlA">
                    <Grid>
                        <FlipView                              VirtualizingStackPanel.VirtualizationMode="Recycling"
                                  ItemsSource="{Binding Items, RelativeSource={RelativeSource TemplatedParent}, Mode=TwoWay}">
                            <FlipView.ItemTemplate>
                                <DataTemplate>
                                    <Grid>
                                        <Canvas
                                                ZIndex="1"
                                                Visibility="Collapsed">
                                                <Border BorderBrush="Black"
                                                    BorderThickness="1">
                                                    <TextBlock Name="CurrentTimeMarkerTB"/> 
                                        </Canvas>
                                    </Grid>
                                </DataTemplate>
                            </FlipView.ItemTemplate>
                        </FlipVIew>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
     </Setter>
</Style>

I want to bind the test property of CurrentTimeMarkerTB to some property of ControlA. I tried

Text="{Binding SomeDateTimePropertyOfControlA, 
       RelativeSource={RelativeSource TemplatedParent},  
       Converter={StaticResource TimelineFormatter},  
       ConverterParameter='0:hh:mm tt', TargetNullValue='CurrentTime'}"

But it never triggeres the converter's TimelineFormatter code.

Upvotes: 0

Views: 113

Answers (1)

nkoniishvt
nkoniishvt

Reputation: 2521

There is no TemplatedParent in a DataTemplate, only in ControlTemplate. You need to retrieve the Parent using FindAncestor:

Text="{Binding SomeDateTimePropertyOfControlA, 
       RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type local:ControlA}},  
       Converter={StaticResource TimelineFormatter},  
       ConverterParameter='0:hh:mm tt', TargetNullValue='CurrentTime'}"

If you can't use FindAncestor mode of RelativeSource you can use ElementName:

Text="{Binding SomeDateTimePropertyOfControlA, 
       ElementName=MyControlA,  
       Converter={StaticResource TimelineFormatter},  
       ConverterParameter='0:hh:mm tt', TargetNullValue='CurrentTime'}"

And then name your control:

<local:ControlA x:Name="MyControlA"/>

Upvotes: 2

Related Questions