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

后端 未结 10 2087
花落未央
花落未央 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:57

    I spent one day to find a solution about this problem of selecting a null value in combobox and finally, yeah finally I found a solution in an article written at this url:

    http://remyblok.tweakblogs.net/blog/7237/wpf-combo-box-with-empty-item-using-net-4-dynamic-objects.html

    public class ComboBoxEmptyItemConverter : IValueConverter 
    { 
    ///  
    /// this object is the empty item in the combobox. A dynamic object that 
    /// returns null for all property request. 
    ///  
    private class EmptyItem : DynamicObject 
    { 
        public override bool TryGetMember(GetMemberBinder binder, out object result) 
        { 
            // just set the result to null and return true 
            result = null; 
            return true; 
        } 
    } 
    
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
        // assume that the value at least inherits from IEnumerable 
        // otherwise we cannot use it. 
        IEnumerable container = value as IEnumerable; 
    
        if (container != null) 
        { 
            // everything inherits from object, so we can safely create a generic IEnumerable 
            IEnumerable genericContainer = container.OfType(); 
            // create an array with a single EmptyItem object that serves to show en empty line 
            IEnumerable emptyItem = new object[] { new EmptyItem() }; 
            // use Linq to concatenate the two enumerable 
            return emptyItem.Concat(genericContainer); 
        } 
    
        return value; 
    } 
    
    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) 
    { 
        throw new NotImplementedException(); 
    } 
    
    
    

    }

     
    

    提交回复
    热议问题