问题的CheckedChanged事件 [英] Issue in CheckedChanged event

查看:658
本文介绍了问题的CheckedChanged事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个复选框,我已经预订了的CheckedChanged事件。处理程序做了一些操作在里面。我检查和编程取消选中该复选框。(例如: chkbx_Name.Checked = TRUE ),和的CheckedChanged事件被炒鱿鱼

I have a check box and I have subscribed for the CheckedChanged event. The handler does some operations in there. I check and uncheck the checkbox programmatically (ex: chkbx_Name.Checked = true), and the CheckedChanged event gets fired.

我想这个事件被解雇,只有当我手动检查或取消选中它。有什么办法避免这种情况,当我检查点火/编程取消呢?

I want this event to be fired only when I manually check or uncheck it. Is there any way to avoid firing of this event when i check/uncheck it programmatically?

推荐答案

订阅您之前设置的事件:

unsubscribe the event before you set:

check1.CheckChanged -= check1_CheckChanged;

,那么你可以通过编程设置的值,而不该复选框烧制的CheckChanged事件:

then you can programmatically set the value without the checkbox firing its CheckChanged event:

check1.Checked = true;

然后重新订阅:

then re-subscribe:

check1.CheckChanged += check1_CheckChanged;

与Tanvi的方法的问题是,你需要捕捉的手动检查所有的源或取消。不是说有太多的(这只是从鼠标点击和用户pressing空格键),但你必须要考虑调用从鼠标点击和KeyUp一个重构事件(检测空格键)

The problem with Tanvi's approach is you need to catch all source of manual check or uncheck. Not that there's too many(it's only from mouse click and from user pressing spacebar), but you have to consider invoking a refactored event from MouseClick and KeyUp(detecting the spacebar)

它更整洁的复选框(为此事任何控制)是不可知的用户输入(键盘,鼠标等)的来源,所以为了这个,我只会让CheckBox的编程设置真正的方案。例如,你可以用该属性的编程设置,以扩展方法:

It's more neat for a CheckBox(any control for that matter) to be agnostic of the source of user input(keyboard, mouse, etc), so for this I will just make the programmatic setting of CheckBox really programmatic. For example, you can wrap the programmatic setting of the property to an extension method:

static class Helper
{
    public static void SetCheckProgrammatically(
        this CheckBox c, 
        EventHandler subscribedEvent, bool b)
    {            
        c.CheckedChanged -= subscribedEvent; // unsubscribe
        c.Checked = b;
        c.CheckedChanged += subscribedEvent; // subscribe
    }
}

使用这种方法,你的code可以通过经由CheckChanged只有一个事件,即整齐响应两个用户的鼠标输入和键盘输入。的code无重复,无需订阅多个事件(如键盘,检查/取消选中复选框以pressing空格键)

Using this approach, your code can respond neatly to both user's mouse input and keyboard input via one event only, i.e. via CheckChanged. No duplication of code, no need to subscribe to multiple events (e.g. keyboard, checking/unchecking the CheckBox by pressing spacebar)

这篇关于问题的CheckedChanged事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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