以编程方式单击按钮并显示按下的动画

本文关键字:动画 显示 编程 方式 单击 按钮 | 更新日期: 2023-09-27 18:20:25

WPF/.NET4我有Button1。它有鼠标悬停和按下的动画。我想用键盘上的键点击按钮。我试过像这样的自动化

ButtonAutomationPeer peer= new ButtonAutomationPeer(Button1);
IInvokeProvider invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
invokeProv.Invoke();

这将引发Button1单击事件处理程序。我也试过这个:

Button1.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));

这两个工作正常,但都没有显示按钮的按下状态。它们引发事件处理程序并运行按钮的内部代码,但不显示按钮被单击时的反应。未显示按下状态。我该怎么做?感谢

以编程方式单击按钮并显示按下的动画

您可以在引发事件之前调用VisualStateManager.GoToState方法。

VisualStateManager.GoToState(Button1, "Pressed", true);
Button1.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));

这样做的问题是动画异步运行,因此引发事件后的任何代码行都将立即执行。绕过它的一种方法是在调用GoToState时获取被调用的Storyboard

为此,您可以使用GetVisualStateGroups

var vsGroups = VisualStateManager.GetVisualStateGroups(VisualTreeHelper.GetChild(Button1, 0) as FrameworkElement);
VisualStateGroup vsg = vsGroups[0] as VisualStateGroup;
if (vsg!= null)
{
    //1 may need to change based on the number of states you have
    //in this example, 1 represents the "Pressed" state
    var vState = vsg.States[1] as VisualState;
    vState.Storyboard.Completed += (s,e)
            {
                VisualStateManager.GoToState(Button1, "Normal", true);
                //Now that the animation is complete, raise the Button1 event
                Button1.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
            };
}
//Animate the "Pressed" visual state
VisualStateManager.GoToState(Button1, "Pressed", true);

您可能想要存储Storyboard(它在vState.Storyboard中,这样您就不必每次都执行搜索,但这应该会让您知道动画何时完成,然后您可以继续执行其余的代码(在这种情况下,我们将引发Button1事件)。