#1,204 – Using a DataTrigger to Change Content in a ContentPresenter

You can set the ContentTemplate property of a ContentPresenter to a panel containing some content, using a DataTemplate.

This technique becomes even more useful when you have different types of content to display, depending on a particular state in your application. In the example below, we set up a Style for a ContentPresenter that sets default content for the ContentPresenter and then swaps in entirely different content when the JobDone property in the data context becomes true.

        <DataTemplate x:Key="DefaultContent">
                <TextBlock Margin="10" Text="Some default content here.."/>
                <TextBlock Margin="10" Text="Maybe show progress for operation"/>

        <DataTemplate x:Key="AllDoneContent">
                <TextBlock Margin="10" Text="** This is the ALL DONE content..."
                <TextBlock Margin="10" Text="Put anything you like here"/>
                <Button Margin="10" Content="Click Me" HorizontalAlignment="Left"/>

        <Style x:Key="MyContentStyle" TargetType="ContentPresenter">
            <Setter Property="ContentTemplate" Value="{StaticResource DefaultContent}"/>
                <DataTrigger Binding="{Binding JobDone}" Value="True">
                    <Setter Property="ContentTemplate" Value="{StaticResource AllDoneContent}"/>
    <Grid Margin="10">
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>

        <ContentPresenter Grid.Row="0" Style="{StaticResource MyContentStyle}" Content="{Binding}"/>
        <Separator Grid.Row="1"/>

        <CheckBox Grid.Row="2" Margin="10" Content="Mark job done" IsChecked="{Binding JobDone}"/>

Here’s how the application looks in the two states. Note that we can toggle between the two states using the CheckBox.


About Sean
Software developer in the Twin Cities area, passionate about .NET technologies. Equally passionate about my own personal projects related to family history and preservation of family stories and photos.

One Response to #1,204 – Using a DataTrigger to Change Content in a ContentPresenter

  1. Pingback: Dew Drop - April 7, 2017 (#2458) - Morning Dew

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: