如何获得不允许选择的收音机盒?

时间:2014-08-05 08:13:33

标签: vb.net winforms

我在面板顶部有一对单选按钮,可用作收音机盒,而且它很好,但是我需要用户可以选择不勾选它们(我希望用户选择)零或一个选项)。在显示表单时,它们都未被选中,但在用户检查其中一个之后,则无法恢复到原始状态。我希望点击选中的单选框可以清除它(我在X / Motif时代依旧记得这一点)但似乎没有发生。

如何对单选按钮进行编程以允许它们不被选中?或者我应该为此目的使用其他控件吗?

3 个答案:

答案 0 :(得分:2)

没有内置的方法可以满足您的需求。做我们自己并不难。以下是示例代码,说明如何执行此操作。

C#版本:

private void Initialize()
{
    radioButton1.AutoCheck = false;
    radioButton2.AutoCheck = false;

    radioButton1.Click += radioButton_Click;
    radioButton2.Click += radioButton_Click;
}

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

    var otherRadios = radio.Parent
                           .Controls
                           .OfType<RadioButton>()
                           .Where(r => r != radio);
    foreach (var r in otherRadios)
    {
        r.Checked = !radio.Checked;
    }
}

Vb.net版本:(使用http://converter.telerik.com/转换)

Private Sub Initialize()
    radioButton1.AutoCheck = False
    radioButton2.AutoCheck = False

    AddHandler radioButton1.Click, AddressOf radioButton_Click
    AddHandler radioButton2.Click, AddressOf radioButton_Click
End Sub
Private Sub radioButton_Click(sender As Object, e As EventArgs)
    Dim radio As RadioButton = DirectCast(sender, RadioButton)
    radio.Checked = Not radio.Checked
    If Not radio.Checked Then
        Return
    End If

    Dim otherRadios = radio.Parent.Controls.OfType(Of RadioButton)().Where(Function(r) r <> radio)
    For Each r As var In otherRadios
        r.Checked = Not radio.Checked
    Next
End Sub

答案 1 :(得分:0)

如果你认为帽子应该很简单..创建你的自定义控件

Imports System.ComponentModel
Public Class MyRadio
    Inherits RadioButton

    Private _permitted As Boolean = True
    <DesignerSerializationVisibility(DesignerSerializationVisibility.Visible)> _
    <Browsable(True)> _
    Public Property Permitted() As Boolean
        Get
            Return _permitted
        End Get
        Set(ByVal value As Boolean)
            _permitted = value
        End Set
    End Property

    Protected Overrides Sub OnClick(ByVal e As System.EventArgs)
        If _permitted Then MyBase.OnClick(e)
    End Sub
End Class

如何使用它?

myRadio1.Permitted = False 'Assigning it to false will not allow you to select it.

答案 2 :(得分:-1)

您可以使用复选框,可以选中和取消选中它们。

如果您确实要取消选中单选按钮,请使用以下代码:

Private Sub RadioButton1_MouseDown(sender As Object, e As MouseEventArgs) Handles RadioButton1.MouseDown
    If RadioButton1.Checked = True Then
        Dim thr As New Threading.Thread(AddressOf unticker)
        thr.Start()
    End If
End Sub
Private Sub unticker()
    Threading.Thread.Sleep(100)
    Do Until RadioButton1.Checked = False
        Invoke(Sub() RadioButton1.Checked = False)
    Loop
End Sub

单独用于每个单选按钮