﻿Imports System.ComponentModel

''' <summary>
''' Provides RadioButton-style functionality in a CheckedListBox.
''' </summary>
<ToolboxBitmap(GetType(CheckedListBox))> _
Public Class RadioCheckedListBox
    Inherits CheckedListBox

    ''' <summary>
    ''' Indicates whether the check boxes behave like radio buttons.
    ''' </summary>
    Private _radioCheck As Boolean = True


    ''' <summary>
    ''' Gets or sets a value that indicates whether the check boxes behave like radio buttons.
    ''' </summary>
    ''' <value>
    ''' <b>true</b> if only one item can be checked at a time; otherwise, <b>false</b>.
    ''' </value>
    <Category("Behavior")> _
    <Description("Indicates whether only a single item can be checked or not.")> _
    <DefaultValue(True)> _
    Public Property RadioCheck() As Boolean
        Get
            Return Me._radioCheck
        End Get
        Set(ByVal value As Boolean)
            If Me._radioCheck <> value Then
                Me._radioCheck = value
                Me.OnRadioCheckChanged(EventArgs.Empty)
            End If
        End Set
    End Property


    ''' <summary>
    ''' Raised when the <see cref="RadioCheck" /> property value changes.
    ''' </summary>
    ''' <remarks></remarks>
    Public Event RadioCheckChanged As EventHandler


    ''' <summary>
    ''' Raises the <see cref="RadioCheckChanged" /> event.
    ''' </summary>
    ''' <param name="e">
    ''' The data for the event.
    ''' </param>
    Protected Overridable Sub OnRadioCheckChanged(ByVal e As EventArgs)
        RaiseEvent RadioCheckChanged(Me, e)
    End Sub

    ''' <summary>
    ''' Raises the <see cref="ItemCheck" /> event.
    ''' </summary>
    ''' <param name="e">
    ''' The data for the event.
    ''' </param>
    ''' <remarks>
    ''' If an item is being checked, all other items are unchecked.
    ''' </remarks>
    Protected Overrides Sub OnItemCheck(ByVal e As System.Windows.Forms.ItemCheckEventArgs)
        If Me._radioCheck AndAlso e.NewValue = CheckState.Checked Then
            'An item is being checked so uncheck all others.
            For index As Integer = 0 To Me.Items.Count - 1
                If index <> e.Index Then
                    Me.SetItemChecked(index, False)
                End If
            Next
        End If

        MyBase.OnItemCheck(e)
    End Sub

End Class
