Reputation: 737
WPF/.NET4 I have Button1. it has MouseOver and Pressed Animations. i want to click the button with a key on keyboard. i have tried Automation like:
ButtonAutomationPeer peer= new ButtonAutomationPeer(Button1);
IInvokeProvider invokeProv = peer.GetPattern(PatternInterface.Invoke) as IInvokeProvider;
invokeProv.Invoke();
this raises the Button1 click event handler. i have tried this too:
Button1.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
these two work fine but none of these show the pressed state of button. they raise event handler and run the inside code of the button but don't show the reaction of the button when it is clicked. Pressed state is not shown. how should i do this? Thanks
Upvotes: 3
Views: 4116
Reputation: 69372
You can call the VisualStateManager.GoToState method before raising the event.
VisualStateManager.GoToState(Button1, "Pressed", true);
Button1.RaiseEvent(new RoutedEventArgs(ButtonBase.ClickEvent));
The problem with this is that animations run asynchronously so any lines of code after the event is raised will execute immediately. One way around it would be to get hold of the Storyboard
that is called when GoToState
is called.
To do this, you can use 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);
You may want to store the Storyboard
(which is in vState.Storyboard
so that you don't have to perform the search each time but this should let you know when the animation is complete and you can then carry on with the rest of the code (in this case we raise the Button1
event).
Upvotes: 3