Question

I have a reference to an instance of a Storyboard object, and want to get hold of the Framework element that it is attached to / animating. I haven't been able to come up with any way of doing this.

For example, in the XAML below, can I go from a reference to the Storyboard to get hold of either the Label or the 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>

For those wondering why on earth I need to do this, it is because I am trying to create a derived Storyboard class or an attached behaviour that will allow me to specify a method name on the DataContext to be called when the Storyboard completed event fires. This will allow me to do pure MVVM rather than needing some code behind to call into my View Model.

Was it helpful?

Solution

If you changed your XAML to something like this:

<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>

This introduces an x:Name to the grid and a Storyboard.Target to the DoubleAnimation. You can now get a reference to the grid with this code:

Storyboard sb = //You mentioned you had a reference to this.
var timeLine = sb.Children.First();
var myGrid = Storyboard.GetTarget(timeLine);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top