如何防止值更改事件在 .NET 中的表单初始化时触发?

编程入门 行业动态 更新时间:2024-10-26 07:36:43
本文介绍了如何防止值更改事件在 .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 中的表单初始化时触发?

本文发布于:2023-11-04 01:21:38,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1556557.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:表单   初始化   如何防止   事件   NET

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!