2009-09-18 102 views
1

我有一个Storyboard对象的实例的引用,并且想要获取它附加到/动画的框架元素。我无法想出任何方法来做到这一点。从故事板获取框架元素

例如,在下面的XAML,我可以从基准到故事板来获得或者标签或电网

<Grid> 
    <Grid.Resources> 
     <Storyboard x:Key="myStoryboard"> 
      <DoubleAnimation Storyboard.TargetProperty="Opacity" From="1" To="0" Duration="0:0:5"/> 
     </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> 

对于那些想知道为什么地球上我需要这样做的保持,这是因为我试图创建派生的Storyboard类或附加的行为,这将允许我在DataContext上指定一个方法名称,以便在Storyboard完成事件触发时调用。这将允许我执行纯MVVM,而不需要使用一些代码来调用我的View Model。

回答

1

如果你改变了你的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:名字到电网和Storyboard.Target到DoubleAnimation是。您现在可以通过此代码获取对网格的引用:

Storyboard sb = //You mentioned you had a reference to this. 
var timeLine = sb.Children.First(); 
var myGrid = Storyboard.GetTarget(timeLine); 
+0

谢谢,它的工作原理!故事板目标应该是labelHello尽管保持行为相同,并且这意味着我不需要命名网格。在我将其标记为答案之前,请等待并看看是否有人可以在不进行XAML更改的情况下执行此操作,因为我希望我的附加属性是唯一需要的标记。 – 2009-09-18 11:30:44