I noticed the other day that Storyboard has a SetTarget method, but it does not have a corresponding GetTarget method. So how can you find the target of a Timeline child? Fortunately, Storybard has a GetTargetName method, we can use this method to obtain the name of the target and then search parent container’s children for a matching child. Suppose we had the following code:
<Grid x:Name="LayoutRoot">
<Grid.Resources>
<Storyboard x:Key="FadeOut">
<DoubleAnimation
To="0"
Duration="0:0:3"
Storyboard.TargetName="TestText"
Storyboard.TargetProperty="(UIElement.Opacity)" />
</Storyboard>
</Grid.Resources>
<TextBlock x:Name="TestText" Text="The Rain In Spain"></TextBlock>
</Grid>
In the example above, the TextBlock TestText is the target of the DoubleAnimation timeline in the FadeOut Storyboard. We can find this using the following code:
var fadeOut = (Storyboard)LayoutRoot.Resources["FadeOut"];
var doubleAnimation = (DoubleAnimation)fadeOut.Children[0];
var targetName = Storyboard.GetTargetName(doubleAnimation);
var target = LayoutRoot.Children.Single(c => ((FrameworkElement)c).Name == targetName);
It is worth noting that you must specify a TargetName, or the GetTargetName method will return null. In other words, if you are creating a Storyboard programmatically, and you only use the SetTarget method instead of the SetTargetName method, the GetTargetName method will not return what you expect:
var sb = new Storyboard();
var da = new DoubleAnimation();
da.To = 0;
da.Duration = TimeSpan.FromSeconds(3);
Storyboard.SetTarget(da, TestText); // Instead try: Storyboard.SetTargetName(da, "TestText");
Storyboard.SetTargetProperty(da, new PropertyPath("(UIElement.Opacity)"));
sb.Children.Add(da);
var target = Storyboard.GetTargetName(da); // Returns null if we don’t call SetTargetName
Enjoy!