How to display a different value for dropdown list values/selected item in a WPF ComboBox?

后端 未结 5 1041
长情又很酷
长情又很酷 2020-11-29 08:22

I have a WPF combobox bound to a list of items with long descriptions.

The type bound to the ComboBox has both short and long description as properties. Currently, I

5条回答
  •  悲哀的现实
    2020-11-29 08:55

    I modified this custom rounded WPF ComboBox to display a different value from the item selected as well as change the color for each item.

    Custom ComboBox

    First you need to create the structure:

    //Structure
    public class COMBOITEM
    {
        string _ITEM_NAME;
        string _ITEM_SHORT_NAME;
        Brush _ITEM_COLOR;
    
        public string ITEM_NAME
        {
            get { return _ITEM_NAME; }
            set { _ITEM_NAME = value; }
        }
    
        public string ITEM_SHORT_NAME
        {
            get { return _ITEM_SHORT_NAME; }
            set { _ITEM_SHORT_NAME = value; }
        }
    
        public Brush ITEM_COLOR
        {
            get { return _ITEM_COLOR; }
            set { _ITEM_COLOR = value; }
        }
    }
    

    Initialize the structure, fill it with data and bind to ComboBox:

    private void Load_Data()
    {
        Brush Normal_Blue = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF1F4E79"));
        //Load first entry
        ObservableCollection _Line_Data = new ObservableCollection();
        _Line_Data.Add(new COMBOITEM() { ITEM_NAME = "Line Number 1", ITEM_SHORT_NAME = "LN 1", ITEM_COLOR = Normal_Blue });
    
        //Load Test Data
        for (int i = 2; i < 10; i++)
        {
            _Line_Data.Add(new COMBOITEM()
            {
                ITEM_NAME = "Line Number " + i.ToString(),
                ITEM_SHORT_NAME = "LN " + i.ToString(),
                ITEM_COLOR = (i % 2 == 0) ? new SolidColorBrush(Colors.Green) : new SolidColorBrush(Colors.Red) //This just changes color
            });
        }
    
        //Bind data to combobox
        cb_Test.ItemsSource = _Line_Data;
    }
    

    Now place the ComboBox in your design. To use it as a normal ComboBox, remove DisplayMemberPath and rename "ColorComboBoxItem" to "CustomComboBoxItem":

    
    

    Now add the following styles/template to App.xaml Application.Resources:

    
    
    
    
        
    
    
    
    
    
    
    
    
    
    
    

    I hope this helps..

提交回复
热议问题