WPF ComboBox initial selection

I ran into a scenario where I needed a WPF ComboBox to be pre-populated when loaded. I couldn’t use SelectedIndex = 1 because I didn’t know if the ComboBox would have any items in it. If there were not any items in the list, it needed to be unselected (SelectedIndex = -1). So I bound the SelectedIndex to the Items.Count property and ran it through a converter.

By interrogating the Items.Count, we can tell if the ComboBox has items in it. If so, we can set the SelectedIndex to be 0 – which makes the first item selected. If Items.Count is 0, we set the SelectedIndex to be -1 – which means no selection.

The analysis happens in the converter. Much like the name suggests, it takes a value, and converts it to a different value. It is a powerful way of changing the behavior of the UI, without cluttering up the code behind. Converters are also decoupled from the XAML and can be used by multiple windows.

Some other converters I use on a regular basis are:
BooleanToVisibleVisiblity – Good way to show an Element if CheckBox.IsChecked = true
ZeroCollapsed – Good way to hid a Listbox if it doesn’t contain any items

Here is the XAML:

<ComboBox ItemsSource="{Binding Source={StaticResource clientProgramManager_GetAll}}"
          SelectedIndex="{Binding RelativeSource={RelativeSource Self},
                         Path=Items.Count,
                         Converter={StaticResource listCountToSelectedIndex},
                         Mode=OneTime}"/>

Here is the converter code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Data;

namespace ParaPlan.Converters
{
    public class ListCountToSelectedIndex : IValueConverter
    {
        #region IValueConverter Members

        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            var listCount = 0;
            int.TryParse(value.ToString(), out listCount);
            if (listCount == 0)
            {
                //no items, make selected index - 1
                return -1;
            }
            //has items, make selected index the first one in the list
            return 0;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            throw new NotImplementedException();
        }

        #endregion
    }
}

2 thoughts on “WPF ComboBox initial selection

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>