如果将XAML更改为以下内容:
<Grid x:Name="grid">
<Grid.Resources>
<Storyboard x:Key="myStoryboard">
<DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:5" Storyboard.Target="{Binding ElementName = grid}"/>
</Storyboard>
<Style x:Key="myStyle" TargetType="{x:Type Label}">
<Style.Triggers>
<DataTrigger
Binding="{Binding Path=StartAnimation}" Value="true">
<DataTrigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource myStoryboard}" />
</DataTrigger.EnterActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Grid.Resources>
<Label x:Name="labelHello" Grid.Row="0" Style="{StaticResource myStyle}">Hello</Label>
</Grid>
这将在网格中引入一个x:Name,并在动画中引入一个故事板.Target。现在,您可以使用以下代码获取对网格的引用:
Storyboard sb =
var timeLine = sb.Children.First();
var myGrid = Storyboard.GetTarget(timeLine);