views:

591

answers:

1

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.

+2  A: 

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;}
    }
}
JC
Not sure why this was downvoted... If there's a better implementation, please provide.
JC
It is a shame there is not a way to achieve this without having to reimplement the property just to add an attribute.
Pondidum