Triggered Content Template

柔情痞子 提交于 2019-12-10 10:27:06

问题


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?


回答1:


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>


来源:https://stackoverflow.com/questions/8886453/triggered-content-template

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!