且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何防止以编程方式更改 RadioButton.Checked 从 TabOrder 中删除控件?

更新时间:2023-10-12 10:54:46

他们已经写了代码来实现这个功能,但是代码有一些bug:

They have written code to implement this feature, but the code has some bug:

当使用 Tab 键在单选按钮组之间移动时,它会尝试选择第一个选中的单选按钮.但是当没有选中的单选按钮时,它会忽略组.

RadioButton 源代码中有一些方法,例如 PerformAutoUpdatesWipeTabStops 负责实现 Tab 键的行为.这些方法检查 AutoCheck 并且它们仅在 AutoChecktrue 的情况下工作.

There are some methods in RadioButton source code like PerformAutoUpdates and WipeTabStops which are responsible to implement the behavior of that Tab key. Those methods check for AutoCheck and they work only in case AutoCheck is true.

因此,如果您想更改行为,只需将 AutoCheck 属性设置为 false 并自行处理所有单选按钮的点击事件并恢复 Checked 自己的财产.

So if you want to change the behavior, it's enough to set AutoCheck property to false and handle click event of all radio buttons yourself and revert the Checked property yourself.

是的,我知道乍一看似乎无关紧要!但就是这样.

private void radioButton_Click(object sender, EventArgs e)
{
    var radio = (RadioButton)sender;
    radio.Checked = !radio.Checked;
}

注意:除了上面的事件处理程序,您还可以创建自己的单选按钮,派生自 RadioButton 并将 AutoCheck 设置为 false 并覆盖 OnClick 并设置 Checked= !Checked.

Note: Instead of above event handler, you also can create your own radio button deriving from RadioButton and set AutoCheck to false and override OnClick and set Checked= !Checked.