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