WPF: ComboBox with reset item

后端 未结 9 1915
长发绾君心
长发绾君心 2020-12-15 23:33

I want to make a ComboBox in WPF that has one null item on the top, when this gets selected, the SelectedItem should be set to null (reset to default state). I\

9条回答
  •  离开以前
    2020-12-16 00:00

    I used the following solution for a similar problem. It makes use of the Converter property of the binding to go back and forth between the internal representation (that null is a reasonable value) and what I want to appear in the ComboBox. I like that there's no need to add an explicit list in a model or viewmodel, but I don't like the fragile connection between the string literal in the converter and that in the ComboBox.

    
        
            
                (none)
                
            
        
    
    

    and then the converter looks like:

    public class MyPropertySelectionConverter : IValueConverter
    {
        public static MyPropertySelectionConverter Instance
        {
            get { return s_Instance; }
        }
    
        public const String NoneString = "(none)";
    
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Object retval = value as MyPropertyType;
            if (retval == null)
            {
                retval = NoneString;
            }
            return retval;
        }
    
        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            Object retval = null;
            if (value is MyPropertyType)
            {
                retval = value;
            }
            else if (String.Equals(NoneString, value as String, StringComparison.OrdinalIgnoreCase))
            {
                retval = null;
            }
            else
            {
                retval = DependencyProperty.UnsetValue;
            }
            return retval;
        }
    
    
        private static MyPropertySelectionConverter s_Instance = new MyPropertySelectionConverter();
    }
    

提交回复
热议问题