How to stop an animation WPF?

2019-04-11 22:48发布

问题:

How to stop an animation so it won't produce Completed event. Here's simple example

<Window x:Class="WpfApplication5.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="248" Width="318">
    <Grid>
        <Border Width="20" Height="20" Background="Red" MouseEnter="Border_MouseEnter" MouseLeave="Border_MouseLeave" x:Name="border" />
    </Grid>
</Window>

And backing code:

private void Border_MouseEnter(object sender, MouseEventArgs e)
{
    var a = new DoubleAnimation { To = 0, Duration = TimeSpan.FromMilliseconds(4000) };
    a.Completed += (obj, args) => MessageBox.Show("Boom!");
    border.BeginAnimation(Border.OpacityProperty, a);
}

private void Border_MouseLeave(object sender, MouseEventArgs e)
{
    border.BeginAnimation(Border.OpacityProperty, null);
    border.Opacity = 1;
}

If I move mouse out before rectangle becomes white it still will display popup window after some time. How to prevent this? Let's assume that Border_MouseLeave and Border_MouseEnter methods doesn't know about each other (they can't pass animation instance variable to each other).

回答1:

you can use this:

<Border Width="20" Height="20" Background="Red" x:Name="border" >
                <Border.Triggers>
                    <EventTrigger RoutedEvent="MouseEnter">
                        <BeginStoryboard Name="Ali">
                            <Storyboard>
                                <DoubleAnimation To="0" Duration="0:0:4" Completed="com" Storyboard.TargetProperty="Opacity"/>
                            </Storyboard>
                        </BeginStoryboard>
                    </EventTrigger>
                    <EventTrigger RoutedEvent="MouseLeave">
                        <StopStoryboard  BeginStoryboardName="Ali"/>
                    </EventTrigger>
                </Border.Triggers>
            </Border>

and :

private void com(object sender, EventArgs e)
        {
            MessageBox.Show("boom!");
        }


回答2:

You could use Property or Data Trigger's EnterActions and ExitActions properties or as @Ali said correctly use Begin and Stop storyboard.