Using WinRTTriggers within data templates
Kaki104 recently commented that they were having a problem using triggers in a certain situation. Helpfully a simple repro was provided – a simple grid view, with an attempt to start a storyboard when an item is clicked:
The trigger had been placed within the data template of the item:
1<DataTemplate x:Key="DataTemplate1">
2 <Grid HorizontalAlignment="Left" Width="250" Height="250">
3 <Grid.Resources>
4 <Storyboard x:Key="storyboard1">
5 <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Border.Background).(SolidColorBrush.Color)" Storyboard.TargetName="border">
6 <EasingColorKeyFrame KeyTime="0" Value="#FFB8B5B5"/>
7 <EasingColorKeyFrame KeyTime="0:0:1" Value="#FF3C3B3B"/>
8 </ColorAnimationUsingKeyFrames>
9 <ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)" Storyboard.TargetName="stackPanel">
10 <EasingColorKeyFrame KeyTime="0" Value="#A69C5151"/>
11 <EasingColorKeyFrame KeyTime="0:0:1" Value="#A6F9F3F3"/>
12 </ColorAnimationUsingKeyFrames>
13 </Storyboard>
14 </Grid.Resources>
15
16 <t:Interactions.Triggers>
17 <t:PropertyChangedTrigger Binding="{Binding Title}">
18 <t:ControlStoryboardAction Action="Start" Storyboard="{StaticResource storyboard1}"/>
19 </t:PropertyChangedTrigger>
20 </t:Interactions.Triggers>
21
22 <Border x:Name="border" Background="#FF3D3D3D"/>
23 <StackPanel x:Name="stackPanel" VerticalAlignment="Bottom" Background="#A6000000">
24 <TextBlock Text="{Binding Title}" Foreground="{StaticResource ListViewItemOverlayForegroundThemeBrush}" Style="{StaticResource TitleTextStyle}" Height="60" Margin="15,0,15,0" LayoutUpdated="TextBlock_LayoutUpdated_1" SelectionChanged="TextBlock_SelectionChanged_1"/>
25 <TextBlock Text="{Binding Subtitle}" Foreground="{StaticResource ListViewItemOverlaySecondaryForegroundThemeBrush}" Style="{StaticResource CaptionTextStyle}" TextWrapping="NoWrap" Margin="15,0,15,10"/>
26 </StackPanel>
27 </Grid>
28</DataTemplate>
Interestingly the designer complains that there is an “illegal qualified name character” in the XAML, but when you run the code, everything works as expected.
Now, I’ve dug around a little and haven’t been able to work out why this is – debugging the host Visual Studio instance doesn’t reveal any exceptions being thrown, so I can only assume the parser is misreporting a problem, though in my experience it’s usually something I’m doing that’s wrong. If anyone can reveal what that is, I’d be very grateful!
A simple workaround for this is to just move the contents of the grid into a separate UserControl and reference that from within the DataTemplate instead:
1<DataTemplate x:Key="DataTemplate1">
2 <local:ItemUserControl />
3</DataTemplate>
This way you don’t get designer errors and everything works at run time.
I’ve uploaded the sample code for this here, if you’re interested.