如何取消选中复选框而不引发事件 [英] How to uncheck Checkbox without raising event
问题描述
我有一个C#项目,其中已经注册了checkox事件.当未选中该复选框时,我将显示一个消息框,提示用户进行确认,如果用户未确认,则该复选框应保留状态(已选中)因此,在代码中,我尝试检查它是否再次引发同一事件.
有没有一种方法可以在不引发事件的情况下更改值
我知道这可以通过取消注册事件,设置值然后重新注册来完成.但是我正在寻找一种更简洁的方法. :doh:
I have a C# project wherein i have registered checkox event.When the checkbox is Unchecked i am displaying a message box which will prompt the user to confirm,if the user does not confirm then the checkbox should retain the state(Checked) So in code i try to check it which again raises the same event.
Is there a way to change the value without raising the event
I know this can be done by un-registering the event,set the value then re-register.but i am looking for a cleaner way. :doh:
推荐答案
public class MyCheckEventArgs: EventArgs {
public bool CurrentState { get; protected set; }
public bool CancelEvent { get; set; }
public MyCheckEventArgs(bool currentState) {
CancelEvent = false;
CurrentState = currentState;
}
}
public class MyCheck : CheckBox {
public EventHandler<MyCheckEventArgs> BeforeChecked;
protected override void OnClick(EventArgs e) {
bool handled = false;
if (BeforeChecked != null) {
MyCheckEventArgs myCheckEventArgs = new MyCheckEventArgs(this.Checked);
BeforeChecked(this, myCheckEventArgs);
handled = myCheckEventArgs.CancelEvent;
}
if (!handled)
base.OnClick(e);
}
}
我相信您可以自己做剩下的事情.
问候,
Alexey
I''m sure the rest you can do by yourself.
Regards,
Alexey
其他人发布的代码无法正常工作有多种原因.
There are multiple reasons why the code someone else posted will not work.
if (UserChangedMind)
CheckBox1.Checked = true;
UserChangedMind = false;
UserChangedMind只是其中之一,因为第二次分配始终在运行,所以它只适用于一微秒.
is just one of them UserChangedMind is only ever true for a microsecond, as the second assignment always runs.
在表单类中尝试这种方式:
Try it this way in your form class:
private bool initialized = false;
public MyForm()
{
InitializeComponents();
this.initialized = true;
}
void checkbox_clickevent(object sender, EventArgs e)
{
// initialized prevents the message box from being displayed in the
// setting is loaded at startup that results in the checkbox being
// unchecked.
if (initialized)
{
CheckBox checkBox = sender as CheckBox;
// this will only ex3cute if the checkbox is unchecked by the user
if (!checkBox.Checked)
{
if (!UserVerified())
{
checkBox.Checked = true;
}
}
}
}
您可能需要稍微调整一下,但我想您明白了.
You may need to tweak this a bit, but I think you get the idea.
这篇关于如何取消选中复选框而不引发事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!