2个活动互相呼唤 [英] 2 events calling each other

查看:62
本文介绍了2个活动互相呼唤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道这个问题有一阵子,但无法真正提出解决方案.我有2个不同的事件处理程序,以递归方式相互调用.一旦事件A被触发,它就会触发事件B,而事件B又会触发事件A,依此类推...

I was wondering about this problem for a while, but couldn't really come up with a solution. I have 2 different event handlers calling each other recursively. As soon as event A is fired, it triggers event B which triggers event A again and so on...

基本上,我希望能够在RichTextBox中选择文本并在组合框中显示相应的字体大小.从组合框选择其他字体大小时,我希望将其值应用于所选文本.

Basically I want to be able to select text in a RichTextBox and show the corresponding font size in a combo box. When I choose a different font size from the ComboBox, I want it's value to be applied to the selected text.

这2个事件是:

1)RichTextBox中文本的选择更改事件:

1) The selection changed event of text inside a RichTextBox:

private void MyRTB_SelectionChanged(object sender, RoutedEventArgs e)
{
    //Get the font size of selected text and select the concurrent size from the ComboBox.   
}

2)组合框的选定索引已更改事件:

2) The selected index changed event of a Combobox:

private void CmbFont_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
    //Apply the chosen font size to the currently selected text of the RichTextBox.
}

什么是最好的解决方案,以确保他们每个人都只是做自己的事情"而不会触发其他事件呢?

What would be the best solution to make sure they each only "do their thing" and do not fire the other event in doing so?

推荐答案

有时在代码中更改控件的属性会意外触发事件.例如,更改ListBox或ComboBox的数据源将触发 SelectedIndexChanged 事件.使用标志来处理这种情况

Sometimes changing a property of a control in code fires an event unintentionally. Changing the data source of a ListBox or a ComboBox will fire the SelectedIndexChanged event, for example. Use a flag to handle this case

private bool _loading;

...

_loading = true;
// Fill the ComboBox or ListView here
_loading = false;

在事件处理程序中执行此操作

In the event handler do this

private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    if (_loading) return;
    ...
}

这篇关于2个活动互相呼唤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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