如何从level0模板化父级绑定level2模板化子级的属性

时间:2016-01-22 07:31:30

标签: c# wpf data-binding

我为自定义控件定义了一个Control模板,说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>

我想将CurrentTimeMarkerTB的test属性绑定到ControlA的某个属性。我试过了

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

但它永远不会触发转换器的TimelineFormatter代码。

1 个答案:

答案 0 :(得分:2)

DataTemplate中没有TemplatedParent,仅在ControlTemplate中。您需要使用FindAncestor检索Parent:

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

如果你不能使用RelativeSource的FindAncestor模式,你可以使用ElementName:

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

然后命名你的控件:

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