Although the answer that proposes attaching the animation directly to the element to be animated solves this problem in simple cases, this isn't really workable when you have a complex animation that needs to target multiple elements. (You can attach an animation to each element of course, but it gets pretty horrible to manage.)
So there's an alternative way to solve this that lets you use a DataTrigger
to run an animation that targets named elements.
There are three places you can attach triggers in WPF: elements, styles, and templates. However, the first two options don't work here. The first is ruled out because WPF doesn't support the use of a DataTrigger
directly on an element. (There's no particularly good reason for this, as far as I know. As far as I remember, when I asked people on the WPF team about this many years ago, they said they'd have liked to have supported it but didn't have time to make it work.) And styles are out because, as the error message you've reported says, you can't target named elements in an animation associated with a style.
So that leaves templates. And you can use either control or data templates for this.
<ContentControl>
<ContentControl.Template>
<ControlTemplate TargetType="ContentControl">
<ControlTemplate.Resources>
<Storyboard x:Key="myAnimation">
<!-- Your animation goes here... -->
</Storyboard>
</ControlTemplate.Resources>
<ControlTemplate.Triggers>
<DataTrigger
Binding="{Binding MyProperty}"
Value="DesiredValue">
<DataTrigger.EnterActions>
<BeginStoryboard
x:Name="beginAnimation"
Storyboard="{StaticResource myAnimation}" />
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<StopStoryboard
BeginStoryboardName="beginAnimation" />
</DataTrigger.ExitActions>
</DataTrigger>
</ControlTemplate.Triggers>
<!-- Content to be animated goes here -->
</ControlTemplate>
</ContentControl.Template>
<ContentControl>
With this construction, WPF is happy to let the animation refer to named elements inside the template. (I've left both the animation and the template content empty here - obviously you'd populate that with your actual animation nd content.)
The reason this works in a template but not a style is that when you apply a template, the named elements it defines will always be present, and so it's safe for animations defined within that template's scope to refer to those elements. This is not generally the case with a style, because styles can be applied to multiple different elements, each of which may have quite different visual trees. (It's a little frustrating that it prevents you from doing this even in scenarios when you can be certain that the required elements will be there, but perhaps there's something that makes it very difficult for the animation to be bound to the named elements at the right time. I know there are quite a lot of optimizations in WPF to enable elements of a style to be reused efficiently, so perhaps one of those is what makes this difficult to support.)