4

I'm trying to set up a ContentTemplate that changes based on a DataTrigger. Syntatically, I feel like this should work, but it results in a stack overflow when trying to render the page:

<ItemsControl ItemsSource="{Binding Path=ExtendedFieldCollection}" ItemTemplate="{StaticResource RequiredFieldsTemplate}" />

<!--Where-->
<DataTemplate x:Key="RequiredFieldsTemplate">
    <ContentPresenter>
        <ContentPresenter.Style>
            <Style TargetType="ContentPresenter">
                <Setter Property="ContentTemplate" Value="{x:Null}"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsRequired}" Value="True">
                        <Setter Property="ContentTemplate" Value="{StaticResource MyFieldDisplayTemplate}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ContentPresenter.Style>
    </ContentPresenter>
</DataTemplate>

Simply going

<DataTemplate x:Key="RequiredFieldsTemplate">
    <ContentPresenter ContentTemplate="{StaticResource MyFieldDisplayTemplate}" />

Works fine - but what I'm trying to accomplish is to bind to a list of fields, but only display the required fields. I can't just use Visibility=collapsed, there is huge overhead in instantiating all the custom controls in the MyFieldDisplayTemplate. My goal is to have non-required fields have a completely different (empty) control template in the ItemsControl.

Any ideas on how to set up this trigger?

Alain
  • 26,663
  • 20
  • 114
  • 184

1 Answers1

9

I figured it out thanks to stumbling upon this question: WPF: How to set the data template trigger for content control?

I should be using a ContentControl - not a ContentPresenter. Strange, the two behave the same when you use them one way, but completely differently when you want to use triggers. Much to learn as always.

<DataTemplate x:Key="RequiredFieldsTemplate">
    <ContentControl>
        <ContentControl.Style>
            <Style TargetType="ContentPresenter">
                <Setter Property="ContentTemplate" Value="{x:Null}"/>
                <Style.Triggers>
                    <DataTrigger Binding="{Binding IsRequired}" Value="True">
                        <Setter Property="ContentTemplate" Value="{StaticResource MyFieldDisplayTemplate}" />
                    </DataTrigger>
                </Style.Triggers>
            </Style>
        </ContentControl.Style>
    </ContentControl>
</DataTemplate>
Community
  • 1
  • 1
Alain
  • 26,663
  • 20
  • 114
  • 184