Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

In .net, I have an inherited control:

public CustomComboBox : ComboBox

I simply want to change the default value of DropDownStyle property, to another value (ComboBoxStyle.DropDownList) besides the default one specified in the base class (ComboBoxStyle.DropDown).

One might think that you can just add the constructor:

public CustomComboBox()
{
     this.DropDownStyle = ComboBoxStyle.DropDownList;
}

However, this approach will confuse the Visual Studio Designer. When designing the custom Control in Visual Studio, if you select ComboBoxStyle.DropDown for the DropDownStyle it thinks that the property you selected is still the default value (from the [DevaultValue()] in the base ComboBox class), so it doesn't add a customComboBox.DropDownStyle = ComboBoxStyle.DropDown line to the Designer.cs file. And confusingly enough, you find that the screen does not behave as intended once ran.

Well you can't override the DropDownStyle property since it is not virtual, but you could do:

[DefaultValue(typeof(ComboBoxStyle), "DropDownList")]
public new ComboBoxStyle DropDownStyle
{
      set { base.DropDownStyle = value; }
      get { return base.DropDownStyle; }
}

but then you will run into trouble from the nuances of using "new" declarations. I've tried it and it doesn't seem to work right as the visual studio designer gets confused from this approach also and forces ComboBoxStyle.DropDown (the default for the base class).

Is there any other way to do this? Sorry for the verbose question, it is hard to describe in detail.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
316 views
Welcome To Ask or Share your Answers For Others

1 Answer

This looks like it works:

public class CustomComboBox : ComboBox
{
    public CustomComboBox()
    {
        base.DropDownStyle = ComboBoxStyle.DropDownList;
    }

    [DefaultValue(ComboBoxStyle.DropDownList)]
    public new ComboBoxStyle DropDownStyle
    {
        set { base.DropDownStyle = value; Invalidate(); }
        get { return base.DropDownStyle;}
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...