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

后端 未结 10 2074
花落未央
花落未央 2020-12-08 06:11

In WPF, it seems to be impossible to select (with the mouse) a \"null\" value from a ComboBox. Edit To clarify, this is .NET 3.5 SP1.

Here\'s some c

10条回答
  •  天命终不由人
    2020-12-08 06:52

    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()
                  .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;
          }
      }
      
    3. Example of use:

      
      

      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.

      提交回复
      热议问题