Click here to Skip to main content
Licence CPOL
First Posted 6 Sep 2009
Views 23,919
Downloads 527
Bookmarked 17 times

RadioListBox: A ListBox with Radio Buttons (WPF Version)

By Jaime Olivares | 6 Sep 2009
How to implement a templated ListBox with radio buttons instead of the standard selection highlight.

1

2

3
1 vote, 33.3%
4
2 votes, 66.7%
5
4.43/5 - 3 votes
μ 4.43, σa 1.01 [?]

RadioListBoxWPF_Source

RadioListBoxWPF_Source

Introduction

This is the WPF version of my previous articles: CRadioListBox: A ListBox with Radio Buttons (MFC Version) and RadioListBox: A ListBox with Radio Buttons (WinForms Version). As explained in those articles, RadioListBox has the same functionalities as a regular ListBox, but with a different look and feel. Anyway, the RadioListBox control offers some advantages:

  • It is clearer that options are mutually exclusive with radio buttons.
  • It is a good alternative to a group of radio buttons because you have to maintain just one control, less memory use.
  • It inherits some useful features like scrolling, sorting, data binding, and multi-column.
  • It will be easier to change options dynamically, as shown in the demo application.
  • It will be easier to manage selection events, also shown in the demo application.

Using the Code

To implement RadioListBox into your project, you just need to do a few steps:

  • Include RadioListBox.xaml and RadioListBox.xaml.cs into your project.
  • Drop a RadioListBox object into your XAML form, or do it by hand. An alias for the System.Windows.Controls.Custom namespace will be useful.
  • Change the standard properties of the control, just like for a ListBox.
  • Use the IsTransparent property to mimic a group of RadioButtons.

That's all! Now you can use the radio button collection as a regular ListBox. You can add items with the Items.Add() method, the ItemsSource property, or directly into XAML. Finally, query for user selection with the SelectedIndex property. No more one-by-one evaluations.

RadioListBox Internals

The RadioListBox class is derived from WPF's ListBox class with a custom ControlTemplate to remove all undesired ListBox functionalities like selected item's background. To be consistent with the radio button model, multiple selection has been disabled. The resumed XAML implementation is the following:

<ListBox x:Class="System.Windows.Controls.Custom.RadioListBox"
       xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
       xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
       xmlns:s="clr-namespace:System;assembly=mscorlib" >
    <ListBox.Resources>
        <Style x:Key="{x:Type ListBoxItem}" TargetType="ListBoxItem">
            <Setter Property="SnapsToDevicePixels" Value="true"/>
            <Setter Property="OverridesDefaultStyle" Value="true"/>
            <Setter Property="Template">
                <Setter.Value>
                    <ControlTemplate TargetType="ListBoxItem">
                        <RadioButton x:Name="radio" Click="ItemRadioClick">
                            <RadioButton.Content>
                                <ContentPresenter ... />
                            </RadioButton.Content>
                        </RadioButton>
                    </ControlTemplate>
                </Setter.Value>
            </Setter>
        </Style>
    </ListBox.Resources>
    <ListBox.Template>
        <ControlTemplate>
            <Border BorderThickness="0" 
                  Padding="1,1,1,1" 
                  Background="Transparent" 
                  Name="theBorder" 
                  SnapsToDevicePixels="True">
                <ScrollViewer Padding="{TemplateBinding Control.Padding}" 
                              Focusable="False">
                  <ItemsPresenter 
                      SnapsToDevicePixels="{TemplateBinding UIElement.SnapsToDevicePixels}" />
                </ScrollViewer>
            </Border>
            <ControlTemplate.Triggers ... />
        </ControlTemplate>
    </ListBox.Template>
</ListBox>

As the radio buttons inside the ControlTemplate don't change the selection, this has to be done manually inside the ItemRadioClick event. Here, the ItemContainerGenerator property has an important role by converting between the ListBox's items contents and the ListBoxItem presentation object. Here is a summarized C# source code:

namespace System.Windows.Controls.Custom
{
    public partial class RadioListBox : ListBox
    {
        public RadioListBox() { ... }

        public new SelectionMode SelectionMode { ... }

        public bool IsTransparent { ... }

        private void ItemRadioClick(object sender, RoutedEventArgs e)
        {
            ListBoxItem sel = (e.Source as RadioButton).TemplatedParent as ListBoxItem;
            int newIndex = this.ItemContainerGenerator.IndexFromContainer(sel); ;
            this.SelectedIndex = newIndex;
        }

        protected override void OnSelectionChanged(SelectionChangedEventArgs e)
        {
            base.OnSelectionChanged(e);

            CheckRadioButtons(e.RemovedItems, false);
            CheckRadioButtons(e.AddedItems, true);
        }

        private void CheckRadioButtons(System.Collections.IList radioButtons, bool isChecked) 
        {
            foreach (object item in radioButtons)
            {
                ListBoxItem lbi = 
                  this.ItemContainerGenerator.ContainerFromItem(item) as ListBoxItem;

                if (lbi != null)
                {
                    RadioButton radio = lbi.Template.FindName("radio", lbi) as RadioButton;
                    if (radio != null)
                        radio.IsChecked = isChecked;
                }
            }
        }
    }
}

History

  • September 6th, 2009: First version.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Jaime Olivares

Software Developer (Senior)
Freelance (jaimeolivares.com)
Peru Peru

Member


Computer Electronics professional and senior Windows C++ and C# developer with experience in many other programming languages, platforms and application areas including communications, simulation systems, GIS, 3D graphics and mobile platform.
Also have experience in electronic interfaces development, specially for military applications.
Currently intensively working with Visual C# 2010.
Top-100 contributor at Experts-Exchange forum.
Can be reached at jaimeolivares.com

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralBind a DataTable PinmemberMCTimotheus2:48 4 Feb '10  
GeneralRe: Bind a DataTable PinmemberJaime Olivares19:03 7 Feb '10  
GeneralRe: Bind a DataTable PinmemberMCTimotheus21:36 7 Feb '10  
Generala loop "for" Pinmemberpeug7:23 30 Jan '10  
GeneralRe: a loop "for" PinmemberJaime Olivares7:25 31 Jan '10  
JokeRe: a loop "for" Pinmemberpeug7:27 31 Jan '10  
GeneralListBox with checkbox Pinmemberpeug3:03 29 Jan '10  
GeneralRe: ListBox with checkbox PinmemberJaime Olivares7:30 31 Jan '10  
QuestionSpace between radio Pinmemberpeug1:09 29 Jan '10  
AnswerRe: Space between radio Pinmemberpeug7:28 31 Jan '10  
GeneralRe: Space between radio PinmemberJaime Olivares7:32 31 Jan '10  
GeneralBug Pinmembernaish_kewl15:41 30 Nov '09  
GeneralRe: Bug PinmemberJaime Olivares3:20 1 Dec '09  
GeneralRe: Bug Pinmembernaish_kewl12:51 3 Feb '10  
GeneralRe: Bug PinmemberJaime Olivares19:25 7 Feb '10  
GeneralRe: Bug Pinmembernaish_kewl13:07 8 Feb '10  
GeneralRe: Bug PinmemberJaime Olivares13:14 8 Feb '10  
General"Checking" in XAML is better PinmemberGuillaume Leparmentier14:57 6 Sep '09  
GeneralRe: "Checking" in XAML is better PinmemberJaime Olivares16:31 6 Sep '09  
GeneralRe: "Checking" in XAML is better PinmemberGuillaume Leparmentier1:25 7 Sep '09  
GeneralRe: "Checking" in XAML is better PinmemberJaime Olivares4:01 7 Sep '09  
GeneralRe: "Checking" in XAML is better Pinmembernaish_kewl14:23 12 Oct '09  
GeneralRe: "Checking" in XAML is better Pinmemberanhldbk21:07 13 Aug '10  

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Mobile
Web01 | 2.5.120210.1 | Last Updated 6 Sep 2009
Article Copyright 2009 by Jaime Olivares
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid