0

I have a ContentControl which tamplate is changed based on some value in DataContext.

<ContentControl x:Name="params_control">
    <ContentControl.Style>
        <Style TargetType="ContentControl">
            <Style.Triggers>
                <DataTrigger Binding="{Binding Type}" Value="Type1">
                    <Setter Property="Template" Value="{StaticResource template1}" />
                </DataTrigger>
                <DataTrigger Binding="{Binding Type}" Value="Type2">
                        <Setter Property="Template" Value="{StaticResource template2}" />
                </DataTrigger>
            </Style.Triggers>
        </Style>
    </ContentControl.Style>
</ContentControl>

The templates are a grid with a number of TextBlocks and TextBoxes like this:

<ControlTemplate x:Key="template1" TargetType="{x:Type ContentControl}">
    <Grid>
        <TextBlock Text="Period"/>
        <TextBox Text="{Binding Period}"/>
    </Grid>
</ControlTemplate>
<ControlTemplate x:Key="template2" TargetType="{x:Type ContentControl}">
    <Grid>
        <TextBlock Text="Period2"/>
        <TextBox Text="{Binding Period2}"/>
    </Grid>
</ControlTemplate>

Template swithching and databinding works well.

The problem is that I need to loop through the input fields in the currently loaded template to check for validation errors but a call to LogicalTreeHelper.GetChildren(params_control) returns nothing.

Why does LogicalTreeHelper not see templated parent children?

yaugenka
  • 2,602
  • 2
  • 22
  • 41
  • The suggested duplicate of refers to using VisualTreeHelper. Why does LogicalTreeHelper not suit here? – yaugenka Aug 23 '19 at 17:35
  • 1
    Template binding means the actual content will be bound later from a template which is somewhere else. Thus the resulting control from a template is not part of the logical tree, because the logical tree/XAML states your ContentControl has no children - the actual content/children are later inserted via templating. However, in the visual output/tree your templates controls are displayed as children of ContentControl. That's why the VisualTreeHelper works, but the LogicalTreeHelper doesn't. – ckuri Aug 23 '19 at 17:47
  • 1
    Thanks, ckuri. This question should be unmarked from duplicates and your answer should be posted in it, because it answers exactly what I have asked about here. – yaugenka Aug 23 '19 at 17:56

0 Answers0