Creating a simple CheckListBox control in WPF

With .NET Framework 3.0 Microsoft has removed one control that I've liked and used a lot - the CheckListBox. But on the other hand with WPF the developer can easily create his own check list control. Here is how to create one yourself.
Put a simple ListBox in your window:
XAML:
<Window x:Class="winCustomPKChooser"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="CheckListBox Demo" 
        Height="300" Width="300"
    >
    <ListBox x:Name="lstCheckListBox"
             Height="185"
               />
</Window>

The trick is that we will not add simple items to the list box, but instead of that we will add check boxes. Here is a simple function which adds items to our ListBox and hoocks the corresponding events for when items get checked or unchecked:
VB:
Private Sub AddItemsToListBox()
     Dim chkCheckBoxToAdd as CheckBox
     For nLoop as Integer = 1 to 10
       chkCheckBoxToAdd = New CheckBox()
       chkCheckBoxToAdd.IsChecked = False
       chkCheckBoxToAdd.Content = "Item " & nLoop.ToString() 

       AddHandler chkCheckBoxToAdd.Checked _
             , AddressOf lstColumnName_ItemCheck
       AddHandler chkCheckBoxToAdd.Unchecked _
             , AddressOf lstColumnName_ItemUncheck

       lstColumnName.Items.Add(chkCheckBoxToAdd)
     Next
End Sub

Private Sub lstColumnName_ItemCheck(ByVal sender As Object _
    , ByVal e As System.Windows.RoutedEventArgs _ 
                        )
     'Do something when an item gets checked. 
     'If you need for something the checkbox 
     'which was checked use the CType(e.OriginalSource, CheckBox).
End Sub

Private Sub lstColumnName_ItemUncheck(ByVal sender As Object _
    , ByVal e As System.Windows.RoutedEventArgs _
   )
      'Do something when an item gets unchecked. 
      'If you need for something the checkbox 
      'which was unchecked use the CType(e.OriginalSource, CheckBox).
End Sub

Enjoy your own CheckListBox!

Labels: , , ,