ComboBox with empty item?

后端 未结 4 730
悲&欢浪女
悲&欢浪女 2020-11-29 23:00

Suppose we have a DataSource bind to a collection from Database. There is no null item of course. How to add a void item into a ComboBox, so that at first l

4条回答
  •  攒了一身酷
    2020-11-29 23:28

    
        
    
    
    
        
            
                
                
            
        
    
    
    public class ComboBox : System.Windows.Controls.ComboBox
    {
        public static readonly DependencyProperty IsNullableProperty =
            DependencyProperty.Register("IsNullable", typeof(bool), typeof(ComboBox));
    
        public bool IsNullable
        {
            get { return (bool)GetValue(IsNullableProperty); }
            set { SetValue(IsNullableProperty, value); }
        }
    
        public ComboBox()
        {
            Loaded += ComboBox_Loaded;
        }
    
        void ComboBox_Loaded(object sender, RoutedEventArgs e)
        {
    
            if (IsNullable)
            {
                this.ItemContainerStyle = new Style();
    
                this.ItemContainerStyle.Setters.Add(new EventSetter()
                {
                    Event = ComboBoxItem.PreviewMouseUpEvent,
                    Handler = new MouseButtonEventHandler(cmbItem_PreviewMouseUp)
                });
            }
        }
    
        public void cmbItem_PreviewMouseUp(object sender, MouseButtonEventArgs e)
        {
            if (Items.IndexOf(sender as ComboBoxItem) == 0)
            {
                SelectedItem = null;
            }
        }
    }
    

提交回复
热议问题