Why can’t I select a null value in a ComboBox?

Well I recently ran into the same problem with null value for ComboBox.
I’ve solved it by using two converters:

  1. For ItemsSource property: it replaces null values in the collection by any value passed inside converter’s parameter:

    class EnumerableNullReplaceConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            var collection = (IEnumerable)value;
    
            return
                collection
                .Cast<object>()
                .Select(x => x ?? parameter)
                .ToArray();
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            throw new NotSupportedException();
        }
    }
    
  2. For SelectedValue property: this one does the same but for the single value and in two ways:

    class NullReplaceConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value ?? parameter;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            return value.Equals(parameter) ? null : value;
        }
    }
    

Example of use:

<ComboBox 
    ItemsSource="{Binding MyValues, Converter={StaticResource EnumerableNullReplaceConverter}, ConverterParameter="(Empty)"}" 
    SelectedValue="{Binding SelectedMyValue, Converter={StaticResource NullReplaceConverter}, ConverterParameter="(Empty)"}"
    />

Result:

enter image description here

Note:
If you bind to ObservableCollection then you will lose change notifications. Also you don’t want to have more than one null value in the collection.

Leave a Comment