如何防止值更改事件在 .NET 中的表单初始化时触发? [英] How to prevent value changed events from firing on form initialization in .NET?

查看:17
本文介绍了如何防止值更改事件在 .NET 中的表单初始化时触发?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑一个带有几个单选按钮和一个复选框的简单 .NET 表单.

Consider a simple .NET form with a couple of radio buttons and a checkbox.

每个单选按钮都有一个 CheckedChanged 处理程序设置,它根据复选框的状态执行一些操作.

Each of the radio buttons has a CheckedChanged handler setup that performs some action based on the state of the checkbox.

我的问题是,当我初始化要检查的默认单选按钮(从设计器属性窗口)时,会为该单选按钮触发 CheckedChanged 事件,但复选框尚未初始化,所以我要么得到一个空指针处理程序中使用了异常或错误的值.无论哪种方式,除非用户在加载表单后选择一个单选按钮,否则我不希望运行该处理程序代码.

My problem is, when I initialize on the default radiobutton to be checked (from the designer properties window) the CheckedChanged event is fired for that radio button, but the Checkbox hasn't been initialized yet so I either get a null pointer exception or the wrong value is used in the handler. Either way, I don't want that handler code to be run unless the user picks a radio button after the form has been loaded.

我目前通过不初始化单选按钮来解决这个问题,但我最终需要设置该默认值,最好的地方来自设计者.我还可以添加一个布尔字段,该字段在表单完全加载之前不会设置为 true,如果为 false,则不处理事件,但这是一个肮脏的黑客.

I currently get around this by not initializing the radio button, but I need to set that default eventually and the best place is from the designer. I also can add a boolean field that's not set to true until the form is fully loaded and not process the events if that is false, but it's a dirty hack.

我该怎么做才能阻止该处理程序运行其代码?

What can I do to prevent that handler from running its code?

推荐答案

"我也可以放置一个布尔字段,在表单完全加载之前不设置为 true,如果为 false 则不处理事件,但这是一个脏的黑客."

"I also can put a boolean field that's not set to true until the form is fully loaded and not process the events if that is false, but it's a dirty hack."

这也是最简单和最好的方法!

It's also the easist and best way to do it!

假设 .NET 提供了一种巧妙的方法来关闭和关闭所有事件处理程序,直到加载表单.即使只是你正在处理的那些.禁用您想要启用的功能但禁用您没有启用的功能仍然不够灵活.经常发生表单设置并且您希望事件被触发.如果没有事件触发,表单也不会正确构建.

Lets say .NET provides a neat way to turn an and off all the event handlers until the form is loaded. Even just the ones YOU are handling. It would still not be sufficiently flexible to disable what you wanted to enable but disable what you didn't. Often form setups happen and you want the events to fire. Also the form won't build right if no events fire.

这篇关于如何防止值更改事件在 .NET 中的表单初始化时触发?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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