2009-09-18 117 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