如何停止动画WPF

本文关键字:WPF 动画 何停止 | 更新日期: 2023-09-27 18:23:42

如何停止动画,使其不会产生Completed事件。以下是的简单示例

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

支持代码:

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

如果我在矩形变白之前将鼠标移出,一段时间后它仍然会显示弹出窗口。如何防止这种情况发生?假设Border_MouseLeaveBorder_MouseEnter方法彼此不了解(它们不能将动画实例变量传递给彼此)。

如何停止动画WPF

您可以使用这个:

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

和:

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

您可以使用Property或Data Trigger的EnterActions和ExitActions属性,或者正如@Ali所说,正确使用Begin和Stop情节提要。