George
George

Reputation: 1528

In WPF animation set property BeginTime to a static resource

What I want to do is define all the BeginTimes of my Animation using a resource.

For example, I want:

<sys:TimeSpan x:key="SomeResource">... </sys:TimeSpan>

...

<DoubleAnimation BeginTime={StaticResource SomeResource}/>

Obviously sys:TimeSpan is not the correct type to use. How do I define my resource so I can reference it as a resource when defining my animations?

I also want to do this purely in XAML.

Thanks.

Upvotes: 3

Views: 3368

Answers (1)

RandomActsOfCode
RandomActsOfCode

Reputation: 3285

System.TimeSpan is the correct type to use since is this is the type of BeginTime. You can also do the same for Duration (but using the System.Windows.Duration type instead).

Here is an example using a StaticResource in an animation (after 2 seconds, fade in for 1 second):

    <Button Content="Placeholder"
            HorizontalAlignment="Center"
            VerticalAlignment="Center"
            Opacity="0.5">
        <Button.Resources>
            <sys:TimeSpan x:Key="FadeInBeginTime">0:0:2</sys:TimeSpan>
            <Duration x:Key="FadeInDuration">0:0:1</Duration>
        </Button.Resources>
        <Button.Style>
            <Style>
                <Style.Triggers>
                    <EventTrigger RoutedEvent="UIElement.MouseEnter">
                        <BeginStoryboard x:Name="FadeInBeginStoryBoard">
                            <Storyboard>
                                <DoubleAnimation Storyboard.TargetProperty="Opacity"
                                                 To="1"
                                                 BeginTime="{StaticResource FadeInBeginTime}"
                                                 Duration="{StaticResource FadeInDuration}" />
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                    <EventTrigger RoutedEvent="UIElement.MouseLeave">
                        <StopStoryboard BeginStoryboardName="FadeInBeginStoryBoard" />
                    </EventTrigger>
                </Style.Triggers>
            </Style>
        </Button.Style>
    </Button>

Assuming you have declared the sys namespace as:

    xmlns:sys="clr-namespace:System;assembly=mscorlib"

Hope this helps!

Upvotes: 3

Related Questions