从Storyboard获取Framework元素

时间:2009-09-18 09:29:12

标签: wpf xaml mvvm storyboard frameworkelement

我有一个Storyboard对象实例的引用,并希望获得它附加到/动画的Framework元素。我无法想出任何办法。

例如,在下面的XAML中,我是否可以从对Storyboard的引用转到获取Label或Grid

<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类或附加行为,这将允许我在Databoard上指定一个方法名称,以便在Storyboard完成时调用事件火灾。这将允许我做纯MVVM而不需要一些代码来调用我的View模型。

1 个答案:

答案 0 :(得分: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:Name,并向DoubleAnimation引入Storyboard.Target。您现在可以使用以下代码获取对网格的引用:

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