In WPF animation set property BeginTime to a static resource

亡梦爱人 提交于 2021-01-27 11:40:44

问题


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.


回答1:


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!



来源:https://stackoverflow.com/questions/7814091/in-wpf-animation-set-property-begintime-to-a-static-resource

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!