In WPF, I want to programmatically raise a SelectionChanged event on a ComboBox. I've tried the following code but it doesn't work:
myComboBox.RaiseEvent(new RoutedEventArgs(ComboBox.SelectionChangedEvent,
myComboBox));
How can I raise that event?
Thanks
While the other answers here are good practice, they don't actually answer your question. To actually answer your question of programmatically raising a SelectionChangedEvent, you could do something like the following:
RoutedEvent routed = ComboBox.SelectionChangedEvent;
List<ComboBoxItem> remove = new List<ComboBoxItem> {myComboBox.Items[0] as ComboBoxItem},
add = new List<ComboBoxItem> {myComboBox.SelectedItem as ComboBoxItem};
var e = new SelectionChangedEventArgs(routed, remove, add);
myComboBox.RaiseEvent(e);
Or if you wanted to do it in a single command:
myComboBox.RaiseEvent(new SelectionChangedEventArgs(
ComboBox.SelectionChangedEvent,
new List<ComboBoxIem> {myComboBox.Items[0] as ComboBoxItem},
new List<ComboBoxItem> {myComboBox.SelectedItem as ComboBoxItem}));`
Easy as pie. But I agree with @RohitVats and @BradleyDotNet that it would be better to do the same functionality by just creating another method that takes the usual event handler arguments and just call that from any other method.
I'm still going to leave this here in case anyone else doesn't want to take that advice. It's good to know how to raise events this way anyway.
You just said you just need to execute the handler, so you don't need to worry about raising the actual event. Just call the handler (which I'm assuming you have access to since you have access to the combo box itsself):
SelectionChangedHandler(myComboBox, new RoutedEventArgs());
Now thats a bit of a hack, you should really refactor the logic that needs to be rerun into a new function:
private void SelectionChangedHandler(object sender, RoutedEventArgs e)
{
...Stuff that you don't rerun
CommonHandleLogic();
}
private void CommonHandleLogic()
{
...Whatever you do
}
Then you can just call CommonHandleLogic()
instead of trying to raise the event.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With