#1,204 – Using a DataTrigger to Change Content in a ContentPresenter
April 6, 2017 4 Comments
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.
<Window.Resources> <DataTemplate x:Key="DefaultContent"> <StackPanel> <TextBlock Margin="10" Text="Some default content here.."/> <TextBlock Margin="10" Text="Maybe show progress for operation"/> </StackPanel> </DataTemplate> <DataTemplate x:Key="AllDoneContent"> <StackPanel> <TextBlock Margin="10" Text="** This is the ALL DONE content..." Foreground="Green"/> <TextBlock Margin="10" Text="Put anything you like here"/> <Button Margin="10" Content="Click Me" HorizontalAlignment="Left"/> </StackPanel> </DataTemplate> <Style x:Key="MyContentStyle" TargetType="ContentPresenter"> <Setter Property="ContentTemplate" Value="{StaticResource DefaultContent}"/> <Style.Triggers> <DataTrigger Binding="{Binding JobDone}" Value="True"> <Setter Property="ContentTemplate" Value="{StaticResource AllDoneContent}"/> </DataTrigger> </Style.Triggers> </Style> </Window.Resources> <Grid Margin="10"> <Grid.RowDefinitions> <RowDefinition Height="*"/> <RowDefinition Height="Auto"/> <RowDefinition Height="*"/> </Grid.RowDefinitions> <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}"/> </Grid>
Here’s how the application looks in the two states. Note that we can toggle between the two states using the CheckBox.