How to invoke click event in WPF programmatically
By andre
WPF is still relatively new and many developers are only scratching the surface of its abilities. Coming from a different framework, one must learn anew how to do the familiar tasks. Sometimes you need to to trigger a click or some other event for one of your WPF controls, such as a button, a menu or a checkbox, directly from code. There are no methods on the controls to invoke these events explicitly. However there is a simple and generic way to do it which works as fine - just use
RaiseEvent
method like this (assuming you have a MenuItem object called
item
):
var item = new MenuItem();
[...]
item.RaiseEvent(new RoutedEventArgs(MenuItem.ClickEvent));
That’s it. The only thing to be careful with is calling
RaiseEvent
from inside another event handler for the object. And, of course, as any other GUI-related method, this should be done on the GUI thread, otherwise you’ll get a runtime exception.
If you find yourself invoking events from code like this all too often, this might be a perfect time to refactor your design, before things get too complicated and GUI and the underlying business logic become too intertwined.