WPF:以编程方式引发SelectionChangedEvent [英] WPF: Raise programmatically a SelectionChangedEvent

查看:38
本文介绍了WPF:以编程方式引发SelectionChangedEvent的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在WPF中,我想以编程方式在组合框上引发SelectionChanged事件.我已经尝试了以下代码,但是没有用:

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));

我该如何筹办该活动?

谢谢

推荐答案

虽然这里的其他答案是好的做法,但它们实际上并不能回答您的问题.要实际回答以编程方式引发SelectionChangedEvent的问题,您可以执行以下操作:

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}));`

容易做馅饼.但是我同意@RohitVats和@BradleyDotNet的看法,最好是通过创建另一个采用常规事件处理程序参数的方法并从任何其他方法调用该方法来实现相同的功能.

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.

这篇关于WPF:以编程方式引发SelectionChangedEvent的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆