您可以在引发事件之前调用VisualStateManager.GoToState方法。
VisualStateManager.GoToState(Button1, "Pressed", true);
Button1.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
这样做的问题是动画是异步运行的,因此引发事件后的任何代码行都会立即执行。一种解决方法是在Storyboard
被调用时获取GoToState
被调用的内容。
为此,您可以使用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
事件)。