问题
in WPF, I want raise programmatically 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
回答1:
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.
回答2:
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.
回答3:
This came up for me in the context of a ListBox, where the problem could be solved by setting the SelectedItem index. For example :
myComboBox.SelectedItem = 0;
回答4:
By MSDN, A value of negative one (-1) is returned if no item is selected.
,
So give your combobox a default index other than -1,
and switch index to -1 and back to original to invoke the event,
without index really changed:
public static void RaiseSelectionChanged(ComboBox cbx)
{
int index = cbx.SelectedIndex;
cbx.SelectedIndex = -1;
cbx.SelectedIndex = index;
}
来源:https://stackoverflow.com/questions/22718717/wpf-raise-programmatically-a-selectionchangedevent