Looking for a WPF ComboBox with checkboxes

后端 未结 3 2081
灰色年华
灰色年华 2020-11-27 04:13

My google skills fail me. Anyone heard of a control like that for WPF. I am trying to make it look like this (winforms screenshot).

3条回答
  •  庸人自扰
    2020-11-27 04:47

    There is my combobox. I use Martin Harris code and code from this link Can a WPF ComboBox display alternative text when its selection is null?

    
        
            
                
                    
                    
                
            
        
    
    
    

    Small class for datasource:

    public class SelectableObject  {
        public bool IsSelected { get; set; }
        public T ObjectData { get; set; }
    
        public SelectableObject(T objectData) {
            ObjectData = objectData;
        }
    
        public SelectableObject(T objectData, bool isSelected) {
            IsSelected = isSelected;
            ObjectData = objectData;
        }
    }
    

    And there is two handler - one for handling CheckBox clicked and one for forming Text for ComboBox.

    private void OnCbObjectCheckBoxChecked(object sender, RoutedEventArgs e) {
        StringBuilder sb = new StringBuilder();
        foreach (SelectableObject cbObject in cbObjects.Items) 
        {
            if (cbObject.IsSelected)
                sb.AppendFormat("{0}, ", cbObject.ObjectData.Description);
        }
        tbObjects.Text = sb.ToString().Trim().TrimEnd(',');
    }
    
    private void OnCbObjectsSelectionChanged(object sender, SelectionChangedEventArgs e) {
        ComboBox comboBox = (ComboBox)sender;
        comboBox.SelectedItem = null;
    }
    

    For ComboBox.ItemsSource I use

    ObservableCollection> 
    

    where tblObject is type of my object, a list of which I want to display in ComboBox.

    I hope this code is useful to someone!

提交回复
热议问题