How to show text in combobox when no item selected?

前端 未结 16 1342
太阳男子
太阳男子 2020-11-30 06:39

C# & .Net 2.0 question (WinForms)

I have set of items in ComboBox and non of them selected. I would like to show a string on combo \"Pl

16条回答
  •  [愿得一人]
    2020-11-30 07:19

    I could not get @Andrei Karcheuski 's approach to work but he inspired me to this approach: (I added the Localizable Property so the Hint can be translated through .resx files for each dialog you use it on)

     public partial class HintComboBox : ComboBox
    {
        string hint;
        Font greyFont;
    
        [Localizable(true)]
        public string Hint
        {
            get { return hint; }
            set { hint = value; Invalidate(); }
        }
    
        public HintComboBox()
        {
            InitializeComponent();
        }
    
        protected override void OnCreateControl()
        {
            base.OnCreateControl();
    
            if (string.IsNullOrEmpty(Text))
            {
                this.ForeColor = SystemColors.GrayText;
                Text = Hint;
            }
            else
            {
                this.ForeColor = Color.Black;
            }
        }
    
        private void HintComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            if( string.IsNullOrEmpty(Text) )
            {
                this.ForeColor = SystemColors.GrayText;
                Text = Hint;
            }
            else
            {
                this.ForeColor = Color.Black;
            }
        }
    

提交回复
热议问题